简体   繁体   中英

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.

Most correct:

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM