Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  29] [ 6]  / answers: 1 / hits: 22514  / 11 Years ago, tue, september 24, 2013, 12:00:00

I have javascript that generates the following HTML



<div class='rightbox'>
<div class'testBox'>

</div>


</div>


Now i have a button that when pressed should remove the div whos class is testbox. Now even though it is in this case it is not always that the testBox is the first child within the rightbox.



So how do i find and remove it? and then afterwards test if it is present as a child within the rightbox?


More From » html

 Answers
4

Use, e.g., querySelector() to find your element and then a combination of parentNode and removeChild() to delete it.



var el = document.querySelector( '.testBox' );
el.parentNode.removeChild( el );


Example Fiddle






Edit 2018:



In the meanwhile support for remove() has landed (In all browsers, but IE), so the above code can be reduced to the following:



document.querySelector( '.testBox' ).remove();


Note, that you should check, whether the selected node actually exists. Otherwiese both snippets will throw an error.


[#75467] Monday, September 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andrewb

Total Points: 259
Total Questions: 124
Total Answers: 90

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;