| by Arround The Web | No comments

How to Access and Manipulate the HTML DOM Element textContent Property in JavaScript?

While creating websites, there may be a requirement for developers to update the site’s text content from time to time. To achieve this functionality, JavaScript offers a wide range of pre-defined methods and properties. Among these properties, there is a “textContent” property that accesses and manipulates the text content of the targeted element.

This guide will illustrate how to access and manipulate the HTML DOM element “textContent” property in JavaScript.

First, have a look at the basics of the HTML DOM “textContent” property.

What is the HTML DOM “textContent” Property in JavaScript?

The “textContent” is the built-in property that sets, retrieves, and modifies the text of a specified element or node including all of its descendants. The descendants are child elements such as <i>,<b>,<em>, and much more that are used for formatting purposes. While setting the text using the “textContent” property, the descendants of the targeted element are completely replaced with the new text.

Syntax(Set Text Content)

The basic syntax to set the text of an element/node using the “textContent” property is written below:

element.textContent = text | node.textContent = text

The above syntax takes the desired “text” as a value that the user wants to set for an element or node.

Syntax(Get Text Content)

The generalized syntax to return the text of an element or node via the “textContent” property is stated here:

element.textContent | node.textContent

Return Value: The “textContent” property returns the “text” of an element or node with spacing but without its inner HTML tags.

Now use the above-defined syntaxes practically to access and manipulate the “textContent” property.

How to Access and Manipulate the HTML DOM Element “textContent” Property in JavaScript?

Similar to “innerHTML” and “innerText” properties, the “textContent” property also allows the users to set, access, and modify the text of the desired element easily. This section performs all of these operations on an element using the below-stated examples.

Example 1: Applying the “textContent” Property to Access the Element/Node Text

This example applies the “textContent” property to return the text of a particular element or node including all of its children.

HTML Code

<div id="myDiv" onmouseover="getText()" style="border: 3px solid black;width: 400px; padding: 5px 5px; margin: auto;">

<h1>First Heading</h1>

<h2>Second Heading</h2>

<h3>Third Heading</h3>

<h4>Fourth Heading</h4>

<h5>Fifth Heading</h5>

<h6>Sixth Heading</h6>

</div>

In the above lines of HTML code:

  • The “<div>” tag having an id “myDiv” creates a div element that is styled with the following properties border, width, padding(top and bottom, left and right), and margin. It also attaches the “onmouseover” event that invokes the “getText()” function when the user hovers the mouse over it.
  • Inside the div, all of the specified heading(h1,h2,h3,h4,h5, and h6) tags insert the heading elements according to their specified levels.

JavaScript Code

<script>

function getText() {

  var elem= document.getElementById("myDiv");

  alert(elem.textContent);

}

</script>

In the above-written JavaScript code block:

  • Define a function named “getText()”.
  • Inside this function, the “elem” variable applies the “getElementById()” method to access the div element through its id.
  • The “alert()” method creates an alert box that uses the “textContent” property to return the text of the parent div along with all of its dependents.

Output

The below output pops up an alert box showing the text content of the div element:

Example 2: Applying the “textContent” Property to Replace an Element Text Content Including its Descendents

This example shows how the “textContent” property replaces all the children of an element while modifying its text.

HTML Code

<center>

<h1 id="myhead" onclick="modifyText()"><b>This</b> is <span>Heading<span> <i>Element</i></h1>

</center>

In the above-stated lines of code:

  • The “<h1>” tag adds a heading element of level 1 with an attached “onclick” event that invokes the “modifyText()” function when the user clicks on it.
  • The heading element also contains the “<b>”, “<span>”, and “<i>” tags as its descendants. The “<b>” tag is used to bold the enclosed string, the “<span>” tag without any styling property is utilized to apply no styling on the given string, and the “<i>” tag is used to display the specified string as italic.

JavaScript Code

<script>

 var h1 =document.getElementById("myhead");
 console.log(h1);
function modifyText(){
 h1.textContent="Welcome to Linuxhint!";
 console.log(h1)
}

</script>

In the above JavaScript code:

  • The “h1” variable uses the “document.getElementById()” method to access the heading element through its assigned id.
  • The “console.log()” method displays the accessed heading element on the console before changing its content.
  • The function named “modifyText()” uses the “textContent” property to modify the text of the fetched heading element.
  • The last “console.log()” method again displays the “h1” value after modification.

Output

The console clearly shows that all the children of the given heading element have been replaced with the newly specified text upon clicking on it:

Example 3: Applying the “textContent” Property to Modify the Text of Element’s Child

This example uses the “textContent” property to modify the text of the specific element’s child.

HTML Code

<div id="myDiv" style="border: 3px solid black;width: 400px; padding: 5px 5px; margin: auto;">

<center>

<button id="btn" onmouseover="changeText()">Old Button</button>

</center>

</div>

In this scenario:

  • The “div” element has a “button” element that is created with the help of the “<btn>” tag.
  • The button element further contains an assigned id and an “onmouseover” event that calls the “changeText()” function when the mouse hovers over it.

JavaScript Code

<script>

var parentElement = document.getElementById("myDiv");
var target = document.getElementById("btn");
var find_me = parentElement.contains(target);
if(parentElement.contains(target)==true){
 console.log(find_me);
 function changeText(){
 target.textContent = "New Button";
 }
} else {
 console.log("Does not exist")
}

</script>

In the above code snippet:

  • The “parentElement” variable applies the “getElementById()” method to access the parent div element. The “target” variable also utilizes the “getElementById()” method to fetch the added button element using its id.
  • The “find_me” variable uses the “contains()” method to check whether the targeted button element is the child of the div or not. This method will return “true” for “yes” otherwise “false”.
  • The “if-else” statement defines a code block.
  • If the targeted element is the child of the parent element, then the “changeText()” function will change its text via the “textContent” property. Otherwise, the “else” code block will execute to display the specified message using the “console.log()” method.

Output

The console shows a “true” boolean value that verifies the button element is the child of the given div and then its text changes upon hovering the mouse over it:

Difference Between textContent, innerText, and innerHTML Properties?

Generally, the “textContent”, “innerText”, and “innerHTML” properties deal with the text of an element or node in the way of setting and getting it. However, these properties are different from each other based on some factors. This section highlights the main differences between all of them:

Terms “textContent” “innerText” “innerHTML”
Return Type It returns the text of an element including all of its children(formatting tags), CSS hidden text, and space. It does not return the HTML tags of an element. It returns the text content of the targeted HTML element with all of its children(formatting tags). It does not return space, CSS hidden text, and HTML tags except <script> & <style>. It returns the text of an element with all of its children(formatting tags), space, CSS hidden text, as well as its inner HTML tags.
inner HTML It does not display the inner HTML tags of an element. It does not display the inner HTML tags of an element. It displays the inner HTML tags of an element.

Now move on to the practical implementation of the above-stated differences between the “textContent”, “innerText”, and the “innerHTML” properties.

HTML Code

<center>

<h3 id="H3"><b>Welcome</b> to <i>Linuxhint<i> <span>Website</span></h3>

<button onclick="returntextContent()">Access textContent</button>

<button onclick="returninnerText()">Access innerText</button>

<button onclick="returninnerHTML()">Access innerHTML</button>

<pre id="para"></pre>

</center>

The description of the above HTML code is noted here:

  • The “<h3>” tag inserts the level 3 heading with an assigned id “H3” and the formatting tags as its children
  • The “<button>” tag creates a new button with an attached “onclick” event that invokes the specified JavaScript function when the user clicks on it.
  • The empty “<pre>” tag with an id “para” creates a block that shows the output. It preserves the line spaces and breaks of an element and displays its content the same as added in the source code.

JavaScript Code

<script>

function returntextContent() {
 let text = document.getElementById("H3").textContent;
 document.getElementById("para").innerText = text;
}
function returninnerText() {
 let text = document.getElementById("H3").innerText;
 document.getElementById("para").innerText = text;
}
function returninnerHTML() {
 let text = document.getElementById("H3").innerHTML;
 document.getElementById("para").innerText = text;
}

</script>

In the JavaScript code block:

  • The “returntextContent()” function applies the “document.getElementById()” method to access the added heading element through its id. It also uses the “textContent” property to return the accessed heading element text with its spaces, children, as well as hidden text. Once done, then display it in the fetched preformatted text block using the “innerText” property.
  • The “returninnerText()” function uses the “innerText” property to get the text content of the fetched heading element only with its children.
  • The “returninnerHTML()” function utilizes the “innerHTML” property to return the text content of the added heading element along with all of its children, spaces, and inner HTML tags.

Output

The output clearly shows the difference between the “textContent”, “innerText”, and the “innerHTML” properties:

That’s all about accessing and manipulating the HTML DOM element “textContent” property in JavaScript.

Conclusion

To access and manipulate the text of an element use the HTML DOM “textContent” property. This property performs such operations with the help of its basic syntaxes specified according to setting, modifying, and returning the text of the targeted element. It is mostly used to get the text of an element without its inner HTML tags that are utilized for its formatting. This guide has deeply illustrated how to access and manipulate the HTML DOM element via the “textContent” property in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply