Add what is contained in the element along with the array

I am trying to add the contents of each span along with the value in the title attribute.

 <div id="group-wrap" class="group"> <span class="lbracket" title="&f">(</span> <span class="grouptitle" title="&f"> Group </span> <span class="rbracket" title="&f">) </span> <span class="username" title="&f"> Username </span> <span class="col" title="&f">:</span> <span class="text" title="&f"> Helo There! </span> </div> 

Here is what I still have:

 var str = []; $('#group-wrap span').each(function(){ str.push($(this).attr('title')); }); alert(str.join('')); }); 

http://jsfiddle.net/B9QeK/3/

The output is &f&f&f&f&f (the value of each attribute of the header), but the expected result matters plus the content in the gap. The attribute value must be added before the content.

 &f(&fGroup&f)&fUsername: &f text 

How can I get this result?

+4
source share
5 answers

It looks like you are looking

 str.push( this.getAttribute('title'), this.textContent || this.text ); 

For performance reasons, you should not re-create the jQuery object for each individual iteration. Even better, do not use jQuery to get these values.

Jsfiddle

And by the way, you can use jQuerys .map() to make it a little more elegant:

 jQuery(function($){ var str = $('#group-wrap span').map(function(){ return this.getAttribute('title') + this.textContent || this.text; }).get(); alert(str.join('')); }); 

Jsfiddle

Link: .map()

+2
source
 jQuery(function($){ var str = []; $('#group-wrap span').each(function(){ str.push($(this).attr('title') + $(this).text()); }); alert(str.join('')); }); 

Working jsfiddle

text :

Description: Gets the combined text content of each element in the set of matched elements, including their descendants.

docs

+2
source

Just use the text method to get the text content of each span :

 var str = []; $('#group-wrap span').each(function(){ //Push value of title attribute and text content into array: str.push($(this).attr('title') + $(this).text()); }); alert(str.join('')); }); 
+1
source

Your line

 str.push($(this).attr('title')); 

It should look like:

 str.push($(this).attr('title') + $(this).text()); 

Although, it makes two identical calls to $(this) , so you might consider caching:

 var $this = $(this) str.push($this.attr('title') + $this.text()); 
+1
source
 var str = ""; $('#group-wrap span').each(function(){ str+=$(this).attr('title')+$(this).text(); }); alert(str); }); 
+1
source

Source: https://habr.com/ru/post/1395210/


All Articles