Search code examples
javascriptjquerygetelementbyidgetelementsbytagname

Using getElementById and getElementsByTagName together


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.


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