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.

nodeValue

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;
itemText.nodeValue;

The nodeValue property simply returns the content of the node.

innerHTML

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.

textContent

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.

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

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Ad