Edit Node Attributes
If you recall, HTML elements can have many attributes. 'class' and 'id' for one are commonly used attributes. With the DOM api, you can retrieve and set any attribute you want. Even create custom attributes only used on your website. The standard attributes are accessible as property values of an HTMLElement
node. HTMLElement
is a subset of ELEMENT
, it is used to represent any HTML element and contains more properties than the general ELEMENT
object.
className and id
You can directly retrieve and set the Class and ID of an element through the className
and id
properties. The reason class attribute is renamed className
as the property name is because class
is a reserved word in JavaScript and they didn't want the two to conflict. Lets create a button that will change the class of a paragraph and therefore alter its styles. Another button that will make the font bold by giving it an ID.
<body>
<p>Hello World</p>
<button onClick="makeGreen()">
Make Green
</button>
<button onClick="makeBold()">
Make Bold
</button>
<button
</body>
.green {
color: green;
}
#bold {
font-weight: bold;
}
var makeGreen = function () {
var paragraph = document.getElementsByTagName('p')[0];
paragraph.className = 'green';
}
var makeBold = function () {
var paragraph = document.getElementsByTagName('p')[0];
paragraph.id = 'bold';
}
Try it on Repl.
classList
Elements with multiple classes would be easier to interact with using the classList
property. Instead of a space delimited string of class names, classList
provides a few useful methods for you to manipulate the classes.
method | description |
---|---|
add | add(String [, String]) Accepts multiple string values of class names separated by comma to be added to the element. If a class already exists, it will be ignored. |
remove | remove(String [, String]) Accepts multiple string values of class names separated by comma to be removed from the element. If a class doesn't exist, it will be ignored. |
toggle | toggle(String [, condition]) Toggles the class value on the element. If the class doesn't exist, add it and return true. If the class exists, remove it and return false. Accepts a second optional condition argument. If condition is true, add class value, if condition is false, remove class value. |
contains | contains(String) Checks whether the element contains the class value, returns true or false. |
replace | replace(oldClass, newClass) Replaces oldClass with newClass. |
Lets add a button to toggle the green
class in our example web page.
var toggleGreen = function () {
var paragraph = document.getElementsByTagName('p')[0];
paragraph.classList.toggle('green');
}
Try it on Repl.
Toggling an Element to Show
Using the classList
property, we can easily write a function that will only show an element that the user wants to see. An example would be to have a list of paragraphs. When the user clicks a button, it will show the selected paragraph and hide the rest.
<div id="paragraphs">
<p class="hidden">paragprah 1</p>
<p class="hidden">paragprah 2</p>
<p class="hidden">paragprah 3</p>
</div>
<button onClick="show(0)">
Show 1
</button>
<button onClick="show(1)">
Show 2
</button>
<button onClick="show(2)">
Show 3
</button>
.hidden {
display: none;
}
var show = function (index) {
var paragraphs = document.getElementById('paragraphs').children;
for (var i = 0; i < paragraphs.length; i++) {
paragraphs[i].classList.toggle('hidden', index !== i);
}
}
Try it on Repl.
Notice that I used .children
in this example. Similar to .childNodes
, .children
returns a list of nodes contained in a ParentNode
. But .children
only returns ELEMENT nodes, compared to .childNodes
which returns all node types. The object you get from .children
is a HTMLCollection
which doesn't have the forEach
method so we had to use a for
loop.
getAttribute, setAttribute, removeAttribute
I did say you can create any attribute you like on a HTML element. To do this using JavaScript, you need to use the setAttribute
method of an element node. It accepts two arguments, the first one is the attribute name, the second is the value you want to set on this attribute.
paragraph.setAttribute('class', 'green');
Notice the class attribute is represented in its actual name 'class' when using setAttribute
. To get an attribute, use getAttribute
. If the attribute does not exist, it will return null or empty string ""
.
paragraph.getAttribute('class');
// -> green
If you ever need to remove an attribute, use removeAttribute
.
paragraph.removeAttribute('class');
In a situation where you want to add your own custom attribute, I highly recommend prefixing it with data-
. This is a common industry practice to prevent conflict with the standard HTML attributes. Say we have a list of paragraphs and some of them should be colored blue. We can add data-color='blue'
to the paragraph element in the HTML. Then write a simple function to loop over the paragraphs and add a class blue
to the chosen ones.
<div id="paragraphs2">
<p>hello world</p>
<p data-color="blue">hello world</p>
<p>hello world</p>
<p data-color="blue">hello world</p>
</div>
<button onClick="makeParagraphsBlue()">
Make Paragraphs Blue
</button>
.blue {
color: blue;
}
var makeParagraphsBlue = function () {
paragraphs = document.getElementById('paragraphs2').children;
for (var i = 0; i < paragraphs.length; i++) {
var paragraph = paragraphs[i];
if (paragraph.getAttribute('data-color') === 'blue') {
paragraph.classList.add('blue');
}
}
}
Notice we are using .children
here as well, since we only want child nodes that are element nodes.