RemoveChild on li inside ul inside div with id?
I have the following code on a web page:
<div id="emails">
<ul>
<li>email1</li>
<li>email2</li>
</ul>
</div>
<a href="#" onClick="deleteEmail()">click</a>
and I want to delete the first email I tried with this:
function deleteEmail(){
var ul = document.getElementById('emails').getElementsByTagName('ul');
ul.removeChild(ul.childNodes[0]);
}
im kinda new for the Javascript DOM, so if there is a better way to do this, please let me know.
Note. I would like to do this without any js frameworks.
DOM node , , , , , , . <li> <ul> 1.
The DOM for your `email 'div looks like this:
DIV
text( whitespace )
UL
text ( whitespace )
LI
text (email1)
text ( whitespace )
LI
text (email2)
text ( whitespace )
text (whitespace)
That being said, the easiest way is to find <li>which one you want to remove and then delete.
var toRemove = document.
getElementById('emails').
getElementsByTagName('ul')[0].
getElementsByTagName('li')[0];
toRemove.parentNode.removeChild( toRemove );
<div id="emails">
<ul>
<li>email1</li>
<li>email2</li>
</ul>
</div>
<a href="#" onClick="deleteEmail()">click</a>
<!--note that I made it so you actually invoke deleteEmail -->
and I want to delete the first email I tried with this:
function deleteEmail(){
//I believe you meant emails =/
var ul = document.getElementById('emails').getElementsByTagName('ul');
ul.removeChild(ul.getElementsByTagName("li")[0]);
}
If you change the line "email #" to a link ... something like this:
<a href="" onClick="removeElement(this.parentNode);return false">email1</a>
With a similar function.
function removeElement(childElm) {
var parentElm = childElm.parentNode;
parentElm.removeChild(childElm);
}
Although you can use removeElement () without onClick, but I just like the simplicity that it allows.