jQuery - Get content and attributes

jQuery DOM operation

A very important part of jQuery is the ability to operate DOM.

jQuery provides a set of DOM-related methods that make it easy to access and manipulate elements and attributes.


Three simple and practical jQuery methods for DOM operations:

text() - Set or return The text content of the selected element

html() - Sets or returns the content of the selected element (including HTML tags)

val() - Set or return the value of a form field

Demonstrate how to get content through jQuery text() and html() methods:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert("Text: " + $("#test").text());
  });
  $("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
  });
});
</script>
</head>
<body>
<p id="test">这是段落中的 <b>粗体</b> 文本。</p>
<button id="btn1">显示文本</button>
<button id="btn2">显示 HTML</button>
</body>
</html>

Demo How to get the value of the input field through the jQuery val() method:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert("值为: " + $("#test").val());
  });
});
</script>
</head>
<body>
<p>名称: <input type="text" id="test" value="php中文网"></p>
<button>显示值</button>
</body>
</html>

attr() attribute

jQuery attr() method is used to get the attribute value.

Demonstrate how to get the value of the href attribute in the link:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert($("#php").attr("href"));
  });
});
</script>
</head>
<body>
<p><a href="http://www.php.cn" id="php">php中文网</a></p>
<button>显示 href 属性的值</button>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btn").click(function(){ $("div").attr("class","reset"); }); }) </script> <style type="text/css"> div{ width:200px; height:200px; border:1px solid blue; } .font{ font-size:18px; color:yellow; } .bg{ background:pink; } .reset{ color:green; font-size:20px; } </style> </head> <body> <div class="font bg">php.cn欢迎您</div> <button id="btn">点击查看效果</button> </body> </html>
submitReset Code