Prozaker
Prozaker

Reputation: 354

removeChild on a li inside a ul inside a div with an id?

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.

Upvotes: 3

Views: 5338

Answers (5)

Brook Julias
Brook Julias

Reputation: 2105

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.

Upvotes: 1

Warty
Warty

Reputation: 7395

<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]);
}

Upvotes: 1

jimr
jimr

Reputation: 11230

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 );

Upvotes: 1

Aaron Butacov
Aaron Butacov

Reputation: 34327

Most correct:

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

Upvotes: 3

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

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.

Upvotes: 3

Related Questions