I need to .Clone each a to inside the next elment which is ul
How can i do that ?
<ul>
<li>
<a>link<a>
<ul></ul>
<li>
<li>
<a>link<a>
<ul></ul>
<li>
<li>
<a>link<a>
<ul></ul>
<li>
<li>
<a>link<a>
<ul></ul>
<li>
</ul>
I have tried:
$("a").each(function () {
$(this).clone().insertAfter(this).find('ul');
});
The problem is i get the new cloned elment just beside the original one, i wish to insert it inside the next ul elment
thanks
You need to find the next
list, then append
the clone
d element. I also fixed your invalid HTML:
$("a").each(function() { $(this).next("ul").append($(this).clone(true)); });
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <ul> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> </ul>
Valid HTML requires that <ul>
can only have <li>
as a direct descendant (child). A <li>
can have anything within itself, but it needs to end properly with a </li>
. The demo follows the following pattern:
<ul><!------------------------------Main List--> <li><!----------------------------List Item--> <a href='#/'>LINK 1</a><!---Original Link--> <ul><!------------------------Target List--> <li><!--------------------New List Item--> <a href='#/'>LINK 1</a><!--Clone Link--> </li> </ul> </li> ... </ul>
/* .each() <a> Create a .clone() of current <a> Find .next() <ul> .append() the clone to <ul> .wrapInner() of <ul> with a <li> */ $("a").each(function() { var dupe = $(this).clone(true, true); $(this).next('ul').append(dupe).wrapInner(`<li></li>`); });
<ul> <li> <a href='#/'>LINK 1</a> <ul></ul> </li> <li> <a href='#/'>LINK 2</a> <ul></ul> </li> <li> <a href='#/'>LINK 3</a> <ul></ul> </li> <li> <a href='#/'>LINK 4</a> <ul></ul> </li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.