views:

102

answers:

3

Given the following block of HTML:

<ul id="taglist">
<li><a name="45" href="">Product 1</a></li>
<li><a name="1146" href="">Product 2</a></li>
<li><a name="13437" href="">Product 3</a></li>
<li><a name="51" href="">Product 4</a></li>
</ul>

Is it possible for JQUERY to return a STRING, one variable with the name values:

alert(tagliststring);

Would alert: 45,1146,13437,51

Thanks

A: 
var output; 
$('li a').each( function() { output += $(this).attr('name') + ','; });

Please note, this will output an extra , at the end.

Daniel A. White
Is there a way for it not to add a , at the end?
AnApprentice
see @TM's answer.
Daniel A. White
+3  A: 

You can use the each function:

var names = [];
$('#taglist > li > a').each(function() {
    names.push(this.name);
});
var result = names.join(',');
alert(result);

This way, names will be an array filled with each individual name, and result will be the comma-delimited string that you are looking for.

For more information, see the jQuery documentation.

An even smaller way of doing this is to use jQuery's map function:

var names = $('#taglist > li > a').map(function() { return this.name; }).get();
var result = names.join(',');

The first example will probably be easier for people to read and understand.

TM
+4  A: 

Using $.map:

var names = $('#taglist > li > a').map(function() {
  return this.name;
}).get().join(',');
// names will contain the string: "45,1146,13437,51"

The $.map method allows you to pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

After $.map, I use the get method, to obtain a plain JavaScript Array object, where I can finally, call the join method, to generate a string.

Check the above example here.

CMS