简体   繁体   中英

Get text from all spans in div using jQuery

I'm dynamically adding span elements to a div. I want to retrieve the text from all the span elements in the div at a later stage. How do I do this? I'd like to use jQuery, but Javascript is fine I guess.

Section of Javascript creating the span elements:

var x = ui.item.value;

var span = document.createElement("span");
span.innerHTML="       "+x+"";

$("#selected").append(span);

This is inside an on click event. The div is called "selected".

You can try something like this:

 var txt= ""; $("#selected span").each(function(){ txt += $(this).text();//here you get the values from each span inside selected element }); $("body").append(txt);//here append the collected text inside eg body 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="selected"> <span>1</span> <span>1</span> <span>1</span> <span>1</span> </div> 

No need for a .each() or any other loop. Just calling .text() will be enough since, according to the JQuery docs , it:

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

So:

 $("#selected").click(function() { var text = $(this).find("span").text(); alert(text); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div id="selected"> <span>1</span> <span>2</span> <span>3</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