简体   繁体   中英

How do I remove siblings from the DOM?

I have this working code:

  a.parentNode.removeChild(a);

I need to also remove this child's previous sibling, ie the element that comes before it.

How do I update this? Does MDN have documentation on it?

Ok, here is a solution which takes into account that the previous sibling might not be an element node:

var previous = a.previousSibling;

// iterate until we find an element node or there is no previous sibling
while(previous && previous.nodeType !== 1) {
    previous = previous.previousSibling;
}

// if there is a sibling, remove it
if(previous) {
    previous.parentNode.removeChild(previous);
}

Reference: Node.previousSibling [MDN]

You could easily create a function which gives you the previous element node.

I will repeat my comment here:

You can find a reference of all DOM interfaces at MDN , in particular, the Node interface .

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