JavaScript get parent element and write holder div for siblings

前端 未结 3 1762
小蘑菇
小蘑菇 2020-12-16 13:08

I have the following structure:

Content here
Content here&l
相关标签:
3条回答
  • 2020-12-16 13:28

    Seeing as this has to be JavaScript (and not jQuery) and you can only indentify the child1 by id you could do something as crude as this:

    var child1 = document.getElementById("child1"),
        parent = child1.parentNode,
        contents = parent.innerHTML ;
        parent.innerHTML = '<div id="holder">' + contents + '</div>';
    

    Hope this helps...

    0 讨论(0)
  • 2020-12-16 13:42

    He said no jQuery, this sounds like a homework assignment but:

    var el = document.getElementById('child1');
    var parent = el.parentNode;
    parent.innerHTML = '<div id="holder">' + parent.innerHTML + '</div>';
    
    0 讨论(0)
  • 2020-12-16 13:48

    i wrote a litte-snipped to travel through DOM to find the first matching parentNode.

    Hope this helps someone, sometime.

    (/¯◡ ‿ ◡)⊃━☆゚. * ・ 。゚,

    function getFirstParentMatch(element, selector) {
      if (!element) {return element};
      element.matches(selector) || (element = (element.nodeName.toLowerCase() === 'html' ? false : getFirstParent(element.parentNode, selector)));
      return element;    
    }
    
    0 讨论(0)
提交回复
热议问题