04. Modifying text & attributes fields

Let's now talk about accessing and updating text nodes and attribute fields.

Accessing and updating text nodes

First we must select the element that contains the particular text node we want to edit. We can store its reference into a variable, and use the firstChild property to access its text element. Any text within any of our element's children will not be included.


The text of the text node can be accessed using its only property, nodeValue. Through this variable, we may access or update the text node.

var item = querySelector('li');
itemText = item.firstChild;

The nodeValue property simply returns the content of the node.


Another approach is the use innerHTML, which obtains all the text and markup inside of an element. This will access all child elements and the text content within. innerHTML should not be used, as it is not considered a standard by the W3C.


The standard way to accessing text is through the textContent variable.

Setting this node will remove all child elements within, and replace it with the given text.

Using textContent is more powerful than innerHTML, since HTML elements are not parsed; this allows you to to write HTML character within an element.

Accessing and updating attributes

As you should recall, attributes are the properties given to an HTML element. For example, the anchor tag (<a href=""></a>) should always have an href attribute. Let's now look at the methods that are used to access, modify and update these attributes.

True if the element contains the attribute a, otherwise False.
Return value of the attribute a.
setAttribute(a, b)
Set the attribute value a to b.
Removes the a attribute from the element.

Build modern and responsive webpages


Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources