Ask coding questions

← Back to all posts
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.

Answered by ArchieMaclean (613) [earned 5 cycles]
View Answer
Commentshotnewtop
ArchieMaclean (613)

You could use querySelectorAll, like:

document.querySelectorAll('#navbar a:not(#logoid)');

That returns a NodeList which you can convert to an array using es6 notation:

[...document.querySelectorAll('#navbar a:not(#logoid)')]

If you only want the first instance of a tag matching the query, you can using querySelector like:

document.querySelector('#navbar a:not(#logoid)');  // returns first match

Please mark this as the answer if it solved your problem :)

GavHern (64)

@ArchieMaclean Thank you! I'm still unsure how to actually use this, though. I get this in console:

and this is my js:

What am I missing?

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';
});
GavHern (64)

@heyitsmarcus Thank you so much! I wish I could mark you both as the answer...

heyitsmarcus (287)

@GavHern haha no worries! An upvote will suffice! He did all the legwork, and I just came in with a bit of a sweep anyways haha :P

heyitsmarcus (287)

@GavHern Oh and another really cool thing since you're using Vanilla JS, I set up binds for document.querySelector and document.querySelectorAll. And what that means is that I setup, let's say s for querySelector and sa for querySelectorAll like this:

const s = document.querySelector.bind(document);
const sa = document.querySelectorAll.bind(document);

//And then use it like this:
s('#mySelector').style.display = 'block';
//Which is now the same as:
document.querySelector('#mySelector').style.display = 'block';

Thank me later.

mat1 (2498)

You should add a class to all the items in navbar which are not logoid, and then select those with something like getElementsByClassName('navbarElements')