Categories
JavaScript Answers

How to get span value with JavaScript?

Spread the love

Sometimes, we want to get span value with JavaScript.

In this article, we’ll look at how to get span value with JavaScript.

How to get span value with JavaScript?

To get span value with JavaScript, we can use getElementsByTagName.

For instance, we write:

<div id="test">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
</div>

to add a div with spans in it.

Then we write:

const div = document.getElementById("test");
const spans = div.getElementsByTagName("span");

for (const s of spans) {
  console.log(s.innerHTML);
}

to select the div with ID test with getElemetById.

Then we call div.getElementsByTagName with 'span' to select the spans.

Next, we loop through the spans with a for-of loop and log the value of the innerHTML property to log the content of the spans.

Therefore,

"1"
"2"
"3"
"4"

is logged.

Conclusion

To get span value with JavaScript, we can use getElementsByTagName.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *