[英]How should I get 'This is my name ' from multiple spans in js?
<div id='item1'>
<span>This is my name</span>
<span> This is my nickname</span>
Need JS code to fetch a specific span 需要JS代码来获取特定范围
You can use: 您可以使用:
document.getElementById("item1").children[0];
To get the first child of your div (ie the first span) and then use .textContent
on this node to get "This is my name" 要获取div的第一个孩子(即第一个跨度),然后在此节点上使用
.textContent
来获取“这是我的名字”
See working example below: 请参见下面的工作示例:
const firstChild = document.getElementById("item1").children[0]; console.log(firstChild.textContent);
<div id='item1'> <span>This is my name</span> <span> This is my nickname</span> </div>
Or, if you wish to use jQuery: 或者,如果您想使用jQuery:
const firstChild = $("#item1").children().eq(0); console.log($(firstChild).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='item1'> <span>This is my name</span> <span> This is my nickname</span> </div>
:contains()
to select the span which contains the text This is my name
:contains()
选择包含文本的跨度This is my name
$("span:contains(This is my name)").css('color', 'red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span>This is my name</span> <span> This is my nickname</span>
You can use find
with eq
like below. 您可以将
find
与eq
一起使用,如下所示。
var item1 = $('#item1').find('span').eq(0).text(); var item2 = $('#item1').find('span').eq(1).text(); console.log(item1); console.log(item2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='item1'> <span>This is my name</span> <span> This is my nickname</span> </div>
Using jQuery you can use 使用jQuery,您可以使用
$('#item1 > span:first-child').text()
var text = $('#item1 > span:first-child').text(); console.log(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='item1'> <span>This is my name</span> <span> This is my nickname</span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.