简体   繁体   中英

How do I get multiple jquery attr values?

My code: http://codepen.io/vincentccw/pen/ecJDG

Basically what I want to get are all the data attribute values from the attr call data-designer

There are suppose to be 4 of them but I can only get the first one using:

  var dsad = $('ul').attr("data-designer");

How do I fix this?

$('ul').each(function(){
    console.log($(this).attr('data-designer'))
    //you can add to an array also  
});

You can use map() to project the attribute values into an array:

var designers = $("ul").map(function() {
    return $(this).attr("data-designer");
}).get();

You can use each() to interact with each element individually:

$('ul').each(function(){
    console.log($(this).data('designer'));
});

Or you can use map() to create an array of all the values which you can deal with separately:

var designers = $('ul').map(function() {
    return $(this).data('designed');
});
console.log(designers);

Note, I used data to get the data-* attributes as this is quicker than accessing the attributes of the DOM element directly.

You need to use .each()

$('ul').each(function(){
   console.log($(this).attr("data-designer"));
});

Codepen Demo

$('ul').attr("data-designer") just got the attribute for the first ul element. If to get all uls with "data-designer" attribute, try this:

 $('ul[data-designer]').each(function(){
      console.log($(this).attr("data-designer"));
 });

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