1

I cannot seem to read the "data" attribute through JavaScript.

Using MDN documentation, I have set the data attribute in the form "data-ingID" and then I am trying to fetch that data using Javascript with the "querySelector".

My markup with data attribute is:

<li class="recipe__item data-ingID=${ingredient.ing_id}">
            <svg class="recipe__icon">
                <use href="img/icons.svg#icon-check"></use>
            </svg>

            <div class="recipe__count">${formatCount(ingredient.count)}</div>
            <div class="recipe__ingredient">
                <span class="recipe__unit">${ingredient.unit}</span>
                ${ingredient.ingredient}
            </div>
</li>

I am trying to read that data with this code:

console.log(document.querySelector('.recipe__icon').parentElement.dataset.ingID);

I am getting 'undefined' as the result even though I am seeing my ID attribute in the inspector.

7
  • is there any reason for dataset? what about just using .getAttribute('data-ingID') instead? Commented Jul 17, 2019 at 16:58
  • @briosheje because that is standard JavaScript.... Commented Jul 17, 2019 at 17:00
  • key will be ingid and you have a typo with your class name with the quotes. Commented Jul 17, 2019 at 17:00
  • You're missing quotes in class="recipe__item data-ingID=${ingredient.ing_id}". Should be class="recipe__item" data-ingID="${ingredient.ing_id}" Commented Jul 17, 2019 at 17:00
  • No specific reason. I saw it's usage on MDN. I tried getAttribute as well but that is resulting in 'null' Commented Jul 17, 2019 at 17:01

1 Answer 1

3

Your data attribute must be lowercase, and most browsers will adjust it automatically, so you should refer to it with:

document.querySelector('.recipe__icon').parentElement.dataset.ingid

Per MDN (emphasis mine):

The name of a custom data attribute in HTML begins with data-. It must contain only letters, numbers and the following characters: dash (-), dot (.), colon (:), underscore (_) -- but NOT any ASCII capital letters (A to Z).

console.log(document.querySelector('.recipe__icon').parentElement.dataset.ingid);
<ul>
  <li class="recipe__item" data-ingID="${ingredient.ing_id}">
    <svg class="recipe__icon">
                <use href="img/icons.svg#icon-check"></use>
            </svg>

    <div class="recipe__count">${formatCount(ingredient.count)}</div>
    <div class="recipe__ingredient">
      <span class="recipe__unit">${ingredient.unit}</span> ${ingredient.ingredient}
    </div>
  </li>
</ul>

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

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.