JQuery get content and attributes

JQuery obtains detailed knowledge points of content and attributes, as follows:

Three simple and practical jQuery methods for DOM manipulation:

text() - Sets or returns the text content of the selected element

html() - set or return the content of the selected element (including HTML tags)

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

Get content with jQuery text() and html() methods:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/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">This is the <b>bold</b> text in the paragraph. </p>
<button id="btn1">Display text</button>
<button id="btn2">Display HTML</button>
</body>
</html>

 Get the value of the input field with the jQuery val() method:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<script src="https://cdn.staticfile.org/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="csdn"></p>
<button>显示值</button>
</body>
</html>

 

 Get attribute
jQuery attr() method is used to get attribute value.
Get the value of the href attribute in the link:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert($("#csdn").attr("href"));
  });
});
</script>
</head>

<body>
<p><a href="https://www.csdn.net" id="csdn">yazc</a></p>
<button>Display the value of the href attribute</button>
</ body>
</html>

The above are detailed knowledge points for jQuery to obtain content and attributes. 

Guess you like

Origin blog.csdn.net/m0_70819559/article/details/126398157