0

I want to get the value of this div by javascript.

<div class = 'test'> 500 </div>

I tried this to get the 500 value, but it didnt work. Do you have some idea how can I get back 500?

values = document.getElementsByClassName("test").innerText
alert(values)
Viktor
  • 23
  • 3
  • 2
    getElement**s**ByClassName - plural - therefore you're getting an array-like result even if it's only one `document.getElementsByClassName("test")[0].innerText` - there's a big dupe on here though – Bravo Jul 27 '21 at 08:30
  • getElementsByClassName returns a list of elements, you have to be precise and say which element you want. – cloned Jul 27 '21 at 08:31

1 Answers1

0

document.querySelector selects first element. document.querySelector(".test") means to select element that has class of "test"(class="test")

in real world cases you should use document.querySelectorAll(selector) and pick up element by index

example: document.querySelectorAll(".test")[0]

another example: document.getElementsByClassName("test")[0]

Note: Using getElementsByClassName is fine, but modern alternative to getElementsByClassName and getElementsById is querySelectorAll

but for now this code would be fine:

const value = document.querySelector(".test").textContent;
console.log(value);
<div class='test'> 500 </div>
B.Ch.
  • 220
  • 1
  • 10