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>
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>
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>
.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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.