Reputation: 23
This is an example of working with attribute nodes. Why would I need to use attribute nodes when I am accessing the DOM in JavaScript
Learning how to setAtttribute,getAttribute,removeAttribute
Need to know why and when I use this ?
if(document.getElementById("plc").hasAttribute("class"))
penguin.setAttribute("class", "hidden");
var penguin = document.getElementById("plc");
alert(document.getElementById("plc").getAttribute("class"));
Upvotes: 1
Views: 41
Reputation: 427
setAttribute()
for custom attributes you create ie node.className
vs node.userName
. className
is a standard attribute vs userName
is custom. For example, node.setAttribute('userName', 'someName')
vs node.className = 'someName'
.
getAttribute()
gives you back attributes of the DOM vs properties like node.id
. Most of the time the values are the same, but there are cases when they aren't. For example input's checked property: getAttribute()
will retrieve checked/empty string
, but input.checked
will come back with true/false
. There was more discussion on this in this question you can check out getAttribute() versus Element object properties?
removeAttribute()
is simply to remove any attribute instead of setting it to null
. In the official docs it says you should use removeAttribute()
instead of setting the attribute value to null
either directly or using setAttribute(). Many attributes will not behave as expected if you set them to null.
Upvotes: 0
Reputation: 844
getAttribute
, setAttribute
, and removeAttribute
are technically called methods, and they act on the DOM node by manipulating the attributes. The DOM node itself is what you've assigned to your variable penguin (but it should be assigned before you use it).
One common use case has to do with storing bits of data on a node. You can set that information and retrieve it later.
Say you have a couple penguins.
<div id='penguin-crowd'>
<div class='penguin' data-species='emperor'></div>
<div class='penguin' data-species='king'></div>
</div>
Now you want to list their species.
let penguins = document.getElementsByClassName('penguin');
for (let i = 0; i < penguins.length; i++) {
let species = penguin[i].getAttribute('data-species');
console.log(`This penguin's species is ${species}`);
}
Result:
// This penguin's species is emperor
// This penguin's species is king
Add another penguin to the crowd.
let penguinCrowd = document.getElementById('penguin-crowd');
let newPenguin = document.createElement('div');
newPenguin.classList.add('penguin');
newPenguin.setAttribute('data-species','emperor');
penguinCrowd.appendChild(newPenguin);
Now you have
<div id='penguin-crowd'>
<div class='penguin' data-species='emperor'></div>
<div class='penguin' data-species='king'></div>
<div class='penguin' data-species='emperor'></div>
</div>
removeAttribute
removes the whole attribute from a node, so if for some reason that needs to happen, it's your go-to method.
Upvotes: 1