How to add one parent to all child nodes in jquery
This code below works fine for me. However, by clicking the first element [Node 1], it is copied to the target div, but without the parent "UL". The same happens when I directly click on the child node. I mean, if I click on node 1.1, node 1.2, etc., then they have to be committed inside a single "UL" element. those.
this below should be changed to
`<li><span>Node 1.1</span></li><li><span>Node 1.2</span></li>`
(this is what I am getting right now) like
<UL><li><span>Node 1.1</span></li><li><span>Node 1.2</span></li></UL>
the same should happen if you select 'Node 1'.
Any idea? Please, help.
http://jsfiddle.net/fjaLsnLh/7/ Please amend this link.
+3
source to share
3 answers
You can use jquery's wrapAll () method to achieve this.
Syntax:
$(selector).wrapAll(wrappingElement);
$('li').wrapAll('<ul></ul>');
eg:
$(document).ready(function() {
$("button").click(function() {
$("li").wrapAll("<ul></ul>");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<UL>
<li><span>Node 1.1</span>
</li>
<li><span>Node 1.2</span>
</li>
</UL>
<button>Wrap a div element around all p elements</button>
</body>
0
source to share