Home >Web Front-end >JS Tutorial >How to get tag content with jquery

How to get tag content with jquery

藏色散人
藏色散人Original
2020-11-17 10:29:465177browse

Jquery method of obtaining tag content: 1. Use the "$('#id').val()" method to obtain the value of the tag; 2. Use "$('#id').text( )" method to get the text in the middle of the tag; 3. Get the html content in the tag through the "$('#id').html()" method.

How to get tag content with jquery

Recommended: "javascript basic tutorial"

Use jquery to get the value of the tag or the content of the element

$('#标签id').val() 可以用来获取标签的value值,比如 input 标签的value值可以用它获取;
$(&#39;#标签id&#39;).text()可以用来获取标签中间的文本,比如 <span>值1</span>就可以用它获取到值1;
$(&#39;#标签id&#39;).html() 可以用来获取标签中间的html内容,比如<div id="div1"><span>123</span></div>可以用$(&#39;#div1&#39;).html()获取到<span>123</span>;
$(&#39;#标签id&#39;).attr(&#39;属性名&#39;)可以用它来获取标签的指定属性的值,比如<a href="xxx.aspx">xxx</a>就可以用.attr(&#39;href&#39;)获取到xxx.aspx。
jquery提供了三个获得内容的方法: text()、html() 以及 val(),其中前两个可用于解决本问题:
$("label#userid").text(); // 首选,获取label的文本
$("label#userid").html(); // 也可以实现,获取label标签内的所有html标记,一般情况改下label标签内就是文本,所以等效上面的方法

The following is an example demonstration: use the above two methods to obtain the content of the label tag, pay attention to the difference in the final results

Create Html elements

<div class="box">
<span>点击按钮获取label中内容:</span><br>
<div class="content">
<label id="userid">输入用户名</label><input type="text">
</div>
<input type="button" value="获取label中的内容">
</div>

Settings css style

div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;}
div.box span{color:#999;font-style:italic;}
div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;}
h3{display:inline-block;}
input[type=&#39;button&#39;]{height:30px;margin:10px;padding:5px 10px;}

Write jquery code

$(function(){
$("input:button.btn1").click(function() {
alert($("label#userid").text());
});
$("input:button.btn2").click(function() {
alert($("label#userid").html());
});
})

Observe the effect

Use the text() method to get the content in the tag

The above is the detailed content of How to get tag content with jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to round jquery valueNext article:How to round jquery value