1

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?

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure that data() is faster than attr()? It should be slower, at least for the first call, since it has to enumerate all the data- attribute to build its cache.
I haven't done any specific testing but I believe jQuery builds the cache on DOMReady. I am ready to be proved wrong though ;)
From the source code, it looks like it's on the first call (and enumerating everything on DOMReady would lead to a noticeable performance loss IMHO).
2
$('ul').each(function(){
    console.log($(this).attr('data-designer'))
    //you can add to an array also  
});

Comments

2

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

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

Comments

1

You need to use .each()

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

Codepen Demo

Comments

1

$('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"));
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.