开发者

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, i.e. the element that comes before it.

How do I update this? Does MDN have do开发者_如何学编程cumentation 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.


  /**
   * Removes all sibling elements after specified
   * @param {HTMLElement} currentElement
   * @private
   */
  _removeNextSiblings(currentElement) {
    while (!!currentElement.nextElementSibling) {
      currentElement.nextElementSibling.remove();
    }
  }


The following code is to remove all sibling elements except for .me

const node = document.querySelector('.me');
const clone = node.cloneNode(true);

const parentNode = node.parentNode;
parentNode.innerHTML = '';
parentNode.append(clone);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜