<div id='item1'>
<span>This is my name</span>
<span> This is my nickname</span>
需要JS代码才能获取特定的跨度
答案 0 :(得分:1)
您可以使用:
document.getElementById("item1").children[0];
要获取div的第一个孩子(即第一个跨度),然后在此节点上使用.textContent
以获取“这是我的名字”
请参见下面的工作示例:
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>
或者,如果您希望使用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>
答案 1 :(得分:0)
: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>
答案 2 :(得分:0)
您可以将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>
答案 3 :(得分:0)
使用可以使用的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>