2

why can't I get the value of the data-price attribute?

I want to get the data-price value, make conversions, and add it to the html markup I know how to do it in jquery, but not in js

JS code:

let btn = document.getElementById('btn');
let counter = document.getElementById('counter');

btn.addEventListener("click", function () {
    btn.getAttribute('data-price');
    counter.innerHTML = btn;
    console.log(btn);
});

HTML code:

<div class="card" style="width: 18rem;">
    <img src="img/img3.jpg" class="card-img-top" alt="...">
    <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <div  id="price" class="card__price">2499р</div>
        <a href="#" id="btn" data-price="2499" class="btn btn-primary">В корзину</a>
    </div>
</div>

Console:

<a href="#" id="btn" data-price="2499" class="btn btn-primary">В корзину</a>
1
  • It seems that you wanted to assign the value of the attribute before using it. Something like const price = btn.getAttribute('data-price');
    – Shlang
    Commented May 11, 2020 at 10:10

3 Answers 3

2

btn is the element, not the value of the attribute.

You need to assign the result of getAttribute to a variable and use that in the innerHTML.

btn.addEventListener("click", function () {
    var btnValue = btn.getAttribute('data-price');
    counter.innerHTML = btnValue;
    console.log(btnValue);
});
1

You can also use dataset property, can be access like this btn.dataset.price

Example

function myFunction(btn) {
  console.log(btn.dataset.price)
}
  <button onclick="myFunction(this)" data-price="1200">My Button</button>

0

getAttribute() returns the actual data-price attribute value.

let attribute = element.getAttribute(attributeName);

where

  • attribute is a string containing the value of attributeName.
  • attributeName is the name of the attribute whose value you want to get.

You need to the set counter.innerHTML to that value like:

const price = btn.getAttribute('data-price');
counter.innerHTML = price;
console.log(price);

Not the answer you're looking for? Browse other questions tagged or ask your own question.