JavaScript DOM Part 2


In Part 1 of the DOM we discussed using JavaScript to change the HTML of an element. Now we will discuss how to change an attribute of an element.

As a simple example, we could change the color of the text of an element to red. It would be nice if we could set the color of as many elements as we want. We could use CSS for the styling, as shown below.

.javascriptdomredtext {
	color: red;
}
.javascriptdombluetext {
	color: blue;
}

Below is our sample text that we will modify with JavaScript.

This is a paragraph with an id of dom2paragraph


function maketextred() {
	dom2paragraph.setAttribute("class", "javascriptdomredtext");
}
function maketextblue() {
	dom2paragraph.setAttribute("class", "javascriptdombluetext");
}

For some reason this does not work.

Leave a comment

Your email address will not be published. Required fields are marked *