Making changes to objects
Assignment statements
It is possible to change objects by assigning new values for various properties, using an assignment statement such as:
item.textContent = "New text";
This should be used with caution, since this replaces all children of the node item
with a single text node. Similarly, one can use an assignment statement to change the property innerHTML
:
item.innerHTML = "New text";
It too should be used with caution. Although it can be safely used to give new text for a paragraph, when applied to an element that contains other elements, the contained elements will all be lost when replaced by the text.
Make sure you understand the differences among the innerHTML
property, the nodeValue
property, and the textContent
property for both text nodes and other types of nodes.
Changing style
To change the value of a particular style attribute, use an assignment statement such as in the example:
item.style.fontSize = "2em";
Notice that the value assigned is a string.
Alternatively, one can use the method .setAttribute(attribute, value)
, where the first input is the attribute to be set and the second input is the value, such as:
item.setAttribute("style", "color: blue");