~5 Removing Elements~
11/18/2024
Removing Elements with the querySelector
Here we have a <div> tag, inside of that <div> tag, we have a span, and each one of our spans have a different id name.
index.html
Go to the index.html
Write this <div> tag inside of the body
script.js
For this example, we will remove all of the code inside of the script file, except for the first line which sets the constant body to be attached to the body.
We use querySelector is used to find and select a certain element. Here we are using the pound sign to grab the two spans that we created with the named ids.
Now write this Code.
The remove method
We know that this petSpan.remove() is a method, because it has the parenthesis following it. And a method uses the parenthesis to call itself or to say I want you to work now. In this case that work is to remove. And so, it removed the pet from the webpage.
Warning, if you were to remove the parenthesis from the end of the remove statement, it would not work, and it would not work, because it has nothing telling it to work, on top of the fact that you were producing an error in your code.
But below, we do indeed have the parenthesis in place, and so the remove method worked as we expected.
Now let’s check that out in the Inspect mode of the Opera browser. You will notice that the entire span for the #pet element is gone. All we have left standing here, is our span for the #state.
To add the span back into the Web page
We could also add that span back in if we wanted to, now you could maybe see why in code to be able to do this might be desirable. Let’s say if we wanted a header on a page to show Welcome Guest! if a user was not logged in, but then if the user was logged in, we wanted to welcome our Subscriber.
And using our append method again, our dog has reappeared.
And you will notice, that if you pulled out that Inspect element again from the browser, you would see that our entire span has returned.
To remove an element from the Parent
Now let’s say we want to do the same thing but be able to do if from the parent element and not from the specific element itself. You will see that using remove is a bit simpler, and basically does the exact same thing. So, you might decide to just stick with the previous method of doing things. But this option is also available, if you so desire to use it.
This time, we decided to pick on the state, I suppose to be fair to our individual span tags.