chipatama
chipatama

Reputation: 173

Javascript , JQ data type conflict

I have a list of elements which looks something like this

<li class="depuy">
    <a class="comp" data-color="#66" href="#">
        Something
    </a>
</li>

On Backbone render, I want to add a background color to these elements taken from their data attribute. I tried to do this

var som_array = $(".com a");
var som_array_length = som_array.length;
for(var i=0;i<som_array_length;i++)
{
    var som_object = som_array[i].data("color");
    console.log(som_object);
}

But in a console I get this message Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'data' but as you see it has. What can be the problem ?

Upvotes: 1

Views: 125

Answers (2)

pethel
pethel

Reputation: 5537

You must wrap you element in the jQuery set. Otherwise it will just be a dom element without the jQuery functions.

var competitors_array = $(".depuy a");
var competitors_array_length = competitors_array.length;
for(var i=0;i<competitors_array_length;i++)
{
    var competitor_object = $(competitors_array[i]).data("color"); // Like this
    console.log(competitor_object);
}

Upvotes: 0

Richard
Richard

Reputation: 8280

This is because when you access an item within the jQuery object using it's index, you're accessing the actual item, and not the jQuery object which contains the data method.

Try this:

$(".depuy a").each(function() {
    console.log($(this).data('color'));
});

Upvotes: 3

Related Questions