Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Create a List of all LIs Name's

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

like image 278
AnApprentice Avatar asked Oct 18 '25 20:10

AnApprentice


2 Answers

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.

like image 87
TM. Avatar answered Oct 20 '25 08:10

TM.


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.

like image 25
Christian C. Salvadó Avatar answered Oct 20 '25 09:10

Christian C. Salvadó