Question

I have code that looks like so:

<ul id="effects-list" class="effects-list">
    <li data-creative="5">Creative</li>
</ul>

I am attempting to read the data attribute of that above HTML using the following code:

var effectData = document.getElementById("effects-list").getElementsByTagName("li");
var creative = effectData.getAttribute('data-creative');
alert(creative)

The above code doesn't work. It throws the following error:

effectData.getAttribute is not a function

I am using jQuery on the page and originally tried this:

var effectData = $('.effects-list li');

Again, same error.

What do I have wrong and how do I fix this?

Here is a jsFiddle of the code.

Note: There are more li elements on the page and I am reading more data than just one li element. I am trying to avoid having to ad a separate id to each li element if I can help it.

Was it helpful?

Solution

getElementsByTagName() returns a list of elements with the given tag name, so you need to access the element inside this list using []:

var effectData = document.getElementById("effects-list").getElementsByTagName("li")[0];

Updated Fiddle

If you're looking for jQuery solution, you can use .data():

var creative = $('#effects-list').find('li').data('creative');

Updated Fiddle

OTHER TIPS

Try below code

var dataCreative = $("#effects-list li").attr('data-creative');
alert(dataCreative);

This is working JSFiddle.

And if there are multiple li inside ul then you can use .each, see below code

$("#effects-list li").each(function(){
    var dataCreative = $(this).attr('data-creative');
    alert(dataCreative);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top