Search within TutorialsPark

Javascript DOM: Working with Text


Use Javascript DOM text related properties and methods to get and modify Text elements


Javascript DOM : Working with Text

The Javascript DOM Text object represents the text content of an element, it is the child of the element in the document model.

For any element present in the DOM, there will be an HTMLElement Object to represent the element itself and a Text object for the content(or text within the element).

For eg: If an element(say <p>) has some some text content within it then, the HTMLElement object represents the element <p>, while the text content within it is represented by Text object

If an element has child elements and they as well contain text content , then each one of them is handled in the same way.

Table : Members of the Text Object

Member Description Returns
appendData(<string>) Appends the text to the end of the node void
data To get or set the Text string
deleteData(<offset> , <count>) To delete count number of characters beginning at the position of offset void
insertData(<offset>, <string>) To insert Text at the position specified by the offset void
length To return the length or number of characters in the string number
replaceData(<offset>, <count>, <string>) To replace the text beginning at the position of offset through offset + count with the specified text. void
replaceWholeText(<string>) To set or get the value of the id attribute Text
splitText(<number>) To split the text node into text nodes, seperated at the position specified by the offset Text
substringData(<offset>, <count>) To extract a string from the text starting at the position of offset, an continuing until the position of offset + count string
wholeText To return all the text within the string string

In Javascript DOM the Text elements are located by finding their parent element and then moving through their child elements.

This process is a bit complex but there hasn't been a better way to do that as yet.

The Demo below makes use of the Text properties and methods data, length, replaceWholeText() and WholeText

Javascript DOM : Using Text properties and methods

Give it a TRY! » Note: The CSSStyleDeclaration.cssText property is used to show and modify the style properties .


Javascript DOM : Text Object Method appendData()

The below demo uses text related DOM Methods appendData(), insertData(), deleteData(), replaceData(), splitText()

Example: Javascript DOM : Text object Methods

Give it a TRY! » Note: The CSSStyleDeclaration.cssText property is used to show and modify the style properties .