简体   繁体   中英

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

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"

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:

 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. Use selector :contains() to select the span which contains the text 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.

 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

$('#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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM