Reputation: 189
I'm trying to wrap an svg with an "a" element that's also a child of it's parent, but the loop isn't working correctly because all of the svg's are being wrapped with the very first link. I don't know why this is happening. Thanks!
I would link to turn this:
<li>
Topic 1
<svg></svg>
<a href="link1"> </a>
</li>
Into This
<li>
<a href="link1">
Topic 1
<svg></svg>
</a>
</li>
$(document).ready(function () {
$("ul").each(function(){
var link = $(this).find('a').attr('href');
$(this).find('svg').wrap("<a href=" + link + "></a>");
});
});
ul{
display: flex;
}
ul li{
width: 90px;
list-style: none;
}
ul li:hover{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul>
<li>
Topic 1
<svg></svg>
<a href="link1"> </a>
</li>
<li>
Topic 2
<svg></svg>
<a href="link2"></a>
</li>
<li>
Topic 3
<svg></svg>
<a href="link3"></a>
</li>
<li>
Topic4
<svg></svg>
<a href="link4"></a>
</li>
</ul>
</body>
Upvotes: 0
Views: 45
Reputation: 109
Try looping through each 'li' within the 'ul';
$(document).ready(function () {
$("ul li").each(function(){
var link = $(this).find('a').attr('href');
$(this).find('svg').wrap("<a href=" + link + "></a>");
});
});
Upvotes: 1
Reputation: 207900
Loop with .each()
on the <li>
not the <ul>
:
$(document).ready(function() {
$("li").each(function() {
var link = $(this).find('a').attr('href');
$(this).find('svg').wrap("<a href=" + link + "></a>");
});
});
ul {
display: flex;
}
ul li {
width: 90px;
list-style: none;
}
ul li:hover {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
Topic 1
<svg></svg>
<a href="link1"> </a>
</li>
<li>
Topic 2
<svg></svg>
<a href="link2"></a>
</li>
<li>
Topic 3
<svg></svg>
<a href="link3"></a>
</li>
<li>
Topic4
<svg></svg>
<a href="link4"></a>
</li>
</ul>
Upvotes: 1