I am attempting to grab the value of a span attribute but am only successful so far in grabbing the text (which I don’t need in this case).
// I want the value to return "10"
myValue = document.querySelector(".count-total").getElementByID("data-multiply")
console.log(myValue)
<div class="count-total">
<span data-multiply="10">20 Doses</span>
</div>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Target the span
with querySelector
, and then get the multiply
value from the dataset.
const span = document.querySelector('.count-total span');
console.log(span.dataset);
const val = span.dataset.multiply;
console.log(val);
<div class="count-total">
<span data-multiply="10">20 Doses</span>
</div>
Method 2
Use the dataset
attribute: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
const node = document.querySelector(".count-total span[data-multiply]")
console.info(node.dataset.multiply)
<div class="count-total">
<span data-multiply="10">20 Doses</span>
</div>
Method 3
.getElementByID("data-multiply")
is neither syntactically correct nor will it get the data attribute
it is spelled getElementById
but is used when an element has an ID
You need to use the querySelector with the complete path and use the dataset property
// I want the value to return "10"
const myValue = document.querySelector(".count-total span").dataset.multiply;
console.log(myValue)
<div class="count-total">
<span data-multiply="10">20 Doses</span>
</div>
Method 4
getElementById
(note the lower case d
at the end) looks for an element with a matching id="xyz"
value. None of your elements has an id
.
Assuming the span
with data-multiply
is the only (or at least first) element with that data-*
attribute, you can find it with querySelector
using an attribute selector ([data-multiply]
) and read its attribute value via getAttribute
or dataset
:
const element = document.querySelector("[data-multiply]");
const myValue = element.getAttribute("data-multiply");
console.log(myValue);
const myValue2 = element.dataset.multiply;
console.log(myValue2);
<div class="count-total">
<span data-multiply="10">20 Doses</span>
</div>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0