Reputation: 79
I'm having trouble unwrapping the anchor tag from the list item.
I have the following markup:
<ul class="yith-wcan-list yith-wcan ">
<li><a href="#">Item 1</a>
<small class="count">8</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 2</a>
<small class="count">10</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 3</a>
<small class="count">4</small>
<div class="clear"></div>
</li>
</ul>
and I am trying to use jQuery to remove the link from the list item, and surround that list item with that link.
For example my desired code would be:
<ul class="yith-wcan-list yith-wcan ">
<a href="#">
<li>Item 1
<small class="count">8</small>
<div class="clear"></div>
</li>
</a>
<a href="#">
<li>Item 2
<small class="count">10</small>
<div class="clear"></div>
</li>
</a>
<a href="#">
<li>Item 3
<small class="count">4</small>
<div class="clear"></div>
</li>
</a>
</ul>
I have the following javascript code but it does not work:
var Links = jQuery('.yith-wcan-list').find('li a');
jQuery(Links[0]).unwrap();
Upvotes: 1
Views: 473
Reputation: 29463
You can achieve this in jQuery in 4 steps:
detach()
;Working Example:
$(document).ready(function(){
// Remove the text from inside each anchor
for (var i = 0; i < $('li').length; i++) {
$('li').eq(i).prepend($('li a').eq(i).text());
}
// Remove all the anchors
$('a').detach();
// Append new anchors to the unordered list, equal to the number of list items
for (var i = 0; i < $('li').length; i++) {
$('ul').append('<a href="#"></a>');
}
// Append the existing list items to the new anchors
for (var i = 0; i < $('li').length; i++) {
$('a').eq(i).append($('li').eq(0));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="yith-wcan-list yith-wcan ">
<li><a href="#">Item 1</a>
<small class="count">8</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 2</a>
<small class="count">10</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 3</a>
<small class="count">4</small>
<div class="clear"></div>
</li>
</ul>
Upvotes: 1
Reputation: 3495
As @j08691 said, <a>
can't be child of <ul>
. However, if you desire that, I would probably use this kind of approach:
$(document).ready(function(){
$("ul.yith-wcan-list.yith-wcan > li").each(function(){
$(this).children().appendTo($(this).children('a:first'))
$(this).children('a:first').wrapInner('<li>').unwrap()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="yith-wcan-list yith-wcan ">
<li><a href="#">Item 1</a>
<small class="count">8</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 2</a>
<small class="count">10</small>
<div class="clear"></div>
</li>
<li><a href="#">Item 3</a>
<small class="count">4</small>
<div class="clear"></div>
</li>
</ul>
Upvotes: 1