How to get and set text in HTML elements in Javascript

  174 views   6 months ago Javascript

I have noticed that newer Javscript developer confused when get or set text data from the HTML elements. I have also got the same experience. They are confused between input tags and div or p. Sometimes confusing getting and setting text data with HTML data.

In this article, we will discuss about all of these things. So first, let's started with HTML content.

To get HTML data from the elements like <div> or <span>, use innerHTML property of DOM element object.

Example:

<div id="text">
    Hello <span class="world">World!</span>
</div>
<script type="text/javascript">
    var data = document.getElementById('text').innerHTML;
    console.log(data);
    // Hello <span class="world">World!</span>
</script>

If you want to set new HTML content in the selector, use like below:

Example:

<div id="text">
    Hello <span class="world">World!</span>
</div>
<script type="text/javascript">
    var data = document.getElementById('text').innerHTML = '<h1>Hello Earth!</h1>';
    console.log(data);
    // <h1>Hello Earth!</h1>
</script>

Now, To get text data from the elements like <p> or <h1> tag, use textContent property of DOM element object.

Example:

<div id="text">
    Hello <span class="world">World!</span>
</div>
<script type="text/javascript">
    var data = document.getElementById('text').textContent;
    console.log(data);
    // Hello World!
</script>

Same way, you can set new text content in the selected element. Notice that this will remove child HTML tags and set new text.

Example:

<div id="text">
    Hello <span class="world">World!</span>
</div>
<script type="text/javascript">
    var element = document.getElementById('text').textContent = 'Hello Earth!';
    console.log(element);
    // Hello Earth!
</script>

Conclusion

So far we have learned how to get and set text and HTML to different elements.

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]