tags:

views:

121

answers:

5

I have the following code on a webpage:

<div id="emails">
<ul>
<li>email1</li>
<li>email2</li>
</ul>
</div>

<a href="#" onClick="deleteEmail()">click</a>

and I want to remove the first email, i've been trying with this:

function deleteEmail(){
    var ul = document.getElementById('emails').getElementsByTagName('ul');
    ul.removeChild(ul.childNodes[0]);
}

im kinda new to Javascript DOM, so if there's a better way to do it, please let me know.

Note: I would like to do this without any kind of js framework.

+2  A: 

Most correct:

var ul = document.getElementById('emails').getElementsByTagName('ul')[0];
var li = ul.getElementsByTagName('li')[0];
ul.removeChild(li)
Aaron Harun
Yes, this works thanks!
Prozaker
+2  A: 

1) More correct string:

var ul = document.getElementById('emails').getElementsByTagName('ul')[0];

2) Note that in "ul.childNodes[i]" i will be 0 for spaces, 1 for <li>email1</li>, 2 for space etc. You should use ul.getElementsByTagName('li')[i] if you're insterested only in <li>s.

Riateche
Thanks for the extra explanation, really helpful!
Prozaker
+1  A: 

The children of a DOM node include text and comments, not just the elements, so in order to figure out what index the element you want to remove is at, you need to take them into account. In your case, the index of the first <li> in the <ul> is 1.

The DOM for your `email' div looks like:

DIV
  text( whitespace )
  UL
    text ( whitespace )
    LI 
      text (email1)
    text ( whitespace )
    LI
      text (email2)
    text ( whitespace )
  text (whitespace)

That being said, it's probably easiest to directly find the <li> you want to remove and then remove it.

var toRemove = document.
      getElementById('emails').
      getElementsByTagName('ul')[0]. 
      getElementsByTagName('li')[0];

toRemove.parentNode.removeChild( toRemove );
jimr
+1  A: 
<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 remove the first email, i've been trying with this:

function deleteEmail(){
    //I believe you meant emails =/
    var ul = document.getElementById('emails').getElementsByTagName('ul');
    ul.removeChild(ul.getElementsByTagName("li")[0]);
}
ItzWarty
+1  A: 

If you turn the string "email#" into a link... something like this:

<a href="" onClick="removeElement(this.parentNode);return false">email1</a>

With a function similar to this.

function removeElement(childElm) {
  var parentElm = childElm.parentNode;
  parentElm.removeChild(childElm);
}

Though you can use removeElement() without the onClick but I just like the simplicity it allows.

Brook Julias
or just onclick="parentNode.removeChild(this)"
thorn
This was very helpful too, I definitely will use a solution based on this one.
Prozaker
@thorn - That's a very good simple solution. I like it.
Brook Julias