Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Removing Nodes

Check if a certain element exists

I am trying to make this app better by doing a few things here and there to improve myself. However, this has been stumping me up. I am trying to check to see if any more list items are in the html document, if they don't exist i want to set the state of the remove button to disabled. A quick google search provides me with ways to check, but none of them seem to work with what i'm trying. For example:

//if the element(s) do not exist then...
if(/*condition to be checked*/) {
    //disable button
}
Ari Misha
Ari Misha
19,323 Points

Can you be more specific like whaddya have in mind? Maybe then we could help out. (:

~ Ari

2 Answers

For example: like the list items in the video.. when we try to remove one that isn't there, I wanna disable the button with some css. I just cant figure out how to test to see if any <li> tags are still there. All of the solutions from google don't work for me.

//this seems to always return true, no matter if it exists or not after I delete an li with the remove from list button...
var elementExists = document.getElementById("find-me");
Ari Misha
Ari Misha
19,323 Points

Maybe you could do like if (!elementExists) { //code goes here }. Does that makes sense?

Callum Anderson
Callum Anderson
8,837 Points

I had the same idea, and the obvious solution seemed to be document.querySelector('ul').hasChildNodes(). However, this doesn't work because any white space in the HTML is recognised as a child node! I tried to introduce a further test by iterating through document.querySelector('ul').childNodes[], and testing each item in the array to see whether it's "nodeName" was 'LI' (each instance of white space is assigned a nodeName of '#text'). I gave up on this in the end as it was getting far too convoluted for such a simple task!

My solution in the end was far simpler - select the first li under ul. If there isn't one, the selector will return null. Obviously, in practice you'd be more specific with this selector, as there is likely to be more than one ul on the page.

removeItemButton.addEventListener('click', () => {
  if (document.querySelector('ul li') != null) {
    let ul = document.querySelector('ul');
    ul.removeChild(document.querySelector('li:last-child'));
  }
});