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.