Text

In this chapter you will learn:

  1. How to work with DOM text

Working with Text

The text content of an element is represented by a Text object, which is presented as a child of the element in the document model.

NameDescriptionReturns
appendData(string)Appends the string to the end of text.void
dataGets or sets the text.string
deleteData(offset, count) Removes the text from the string.void
insertData(offset, string)Inserts the specified string at the specified offset.void
lengthReturns the number of characters.number
replaceData(offset,count, string)Replaces a region of text with the specified string.void
replaceWholeText(string)Replaces all of the text.Text
splitText(number)Splits the existing Text element into two at the specified offset.Text
substringData(offset, count)Returns a substring from the text.string
wholeTextGets the text.string

The following code replaces the text for a paragraph.

<!DOCTYPE HTML> <!--from j a  v a 2  s. c  om-->
<html> 
<body> 
  <p id="textblock"> 
      This is a test.
  </p> 
  <button id="pressme">Press Me</button> 
  <script> 
    
    var elem = document.getElementById("textblock"); 
    document.getElementById("pressme").onclick = function() { 
      var textElem = elem.firstChild; 
      document.writeln("The element has " + textElem.length + " chars"); 
      textElem.replaceWholeText("This is a new string "); 
    }; 
  </script> 
</body> 
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to get the length of a NodeList
  2. How to Convert NodeList to an Array
  3. Convert a NodeList to an array in Internet Explorer
Home » Javascript Tutorial » DOM
Document Object Model
Node Type
nodeName and nodeValue
childNodes
parentNode
previousSibling and nextSibling
lastChild and firstChild
appendChild
insertBefore
ownerDocument
removeChild
replaceChild
Text
NodeList Length
DOM classes