JavaScript gets the parent element and writes a div holder for siblings
I have the following structure:
<div class="parent">
<div id="child1">Content here</div>
<div class="child2">Content here</div>
</div>
In onload, I want to include a div holder that contains all the parent children:
<div class="parent">
<div id="holder">
<div id="child1">Content here</div>
<div class="child2">Content here</div>
</div>
</div>
Knowing only the identifier "child1", how can I add a div holder around me and my siblings?
Questions
- The identifier "child1" is the only known identifier.
- The class "parent" and "child2" are a dynamic name and will change, so they cannot be used as identifiers.
- must be vanilla javascript.
Thoughts?
+11
3 answers
I wrote a small excerpt to go through the DOM to find the first matching parentNode.
Hope this helps someone someday.
(/ Β―β‘ βΏ β‘) ββ β οΎ. * ο½₯q οΎ,
function getFirstParentMatch(element, selector) {
if (!element) {return element};
element.matches(selector) || (element = (element.nodeName.toLowerCase() === 'html' ? false : getFirstParent(element.parentNode, selector)));
return element;
}
0