How to use getElementById() in Javascript with tag name exception?
GavHern (64)

I have a bit of a tricky scenario. I want to select all of the children of and id #navbar that are <a> tags. I also don't want to select the children with the id #logoid. I have styled them this way with css like this:

#navbar a:not(#logoid) {
    /*Styling rules here*/
}

How could I select the same elements with javascript? I assume I use getElementById() but I'm not sure how to only get the <a> children and exclude the id #logoid. I hope I explained this properly.

You are viewing a single comment. View All
Answered by ArchieMaclean (619) [earned 5 cycles]
View Answer
heyitsmarcus (287)

@GavHern you can't use document.querySelectorAll like that. You can do individual nodes with document.querySelector using direct syntax like that, but document.querySelectorAll won't work with direct syntax like that.

But, what you can do with document.querySelectorAll is just as @ArchieMaclean said, convert the NodeList to an Array and then iterate over the array, causing each element to be block:

[...document.querySelectorAll('#navbar a:not(#logoid)')].forEach(el => {
  el.style.display = 'block';
});