HTML DOM textContent Property



The HTML DOM textContent property returns/sets a string corresponding to the text (including whitespaces) of the node and all its child nodes as well.

Following is the syntax −

Returning string value

Node.textContent

Here, the return value can be the following −

  • ‘Null’ for document nodes
  • Text of specified node and all its child nodes

Set textContent to a string value

Node.textContent = string

NOTE: HTML DOM textContent property sets the text of node and child nodes as a single text string.

Let us see an example of HTML DOM textContent property −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM textContent</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
   ul{
      width: 30%;
      margin: 0 auto;
   }
</style>
</head>
<body>
   <form>
      <fieldset>
         <legend>HTML-DOM-textContent</legend>
         <h3>Students</h3>
         <ul>
            <li>Adam</li>
            <li>Alex</li>
            <li>Bina</li>
            <li>Eden</li>
            <li>Rajesh</li>
            <li>Zampa</li>
         </ul>
         <input type="button" onclick="checkForBina()" value="Confirm for Bina">
         <div id="divDisplay"></div>
      </fieldset>
   </form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var studentList = document.getElementsByTagName("li");
   var status = 'not Present';
   function checkForBina() {
      for(var i=0; i<studentList.length; i++){
         if(studentList[i].childNodes[0].textContent === 'Bina'){
            status = 'Present';
            break;
         }
    }
    divDisplay.textContent = 'Bina is '+status;
   }
</script>
</body>
</html>

Output

Before clicking ‘Confirm for Bina’ button −

After clicking ‘Confirm for Bina’ button −


Advertisements