'Jquery - Assign sibling Element with closest anchor link
I have a page of dynamically loading divs with titles, and links.
I'm trying to grab the link from each of the elements and assign it to a previous span / title / image. I'm having trouble getting this to only use the anchor text within the same parent instead of returning all (in this case both) of the links?
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) {
$('.ancestors').find('.bigp').each(function() {
let link = $(this).find('a.mylink').attr('href');
console.log(link);
$('span.newlink').wrap('<a href="' + link + '"></a>');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="ancestors">body (great-grandparent)
<div style="width:500px;" class="bigp">div (grandparent)
<ul>ul (direct parent)
<li>li (child)
<span class="newlink">google pic</span>
</li>
<li class="findme"><a class="mylink" href="https://google.com">google</a></li>
</ul>
</div>
<div style="width:500px;" class="bigp">div (grandparent)
<ul>ul (direct parent)
<li>li (child)
<span class="newlink">yahoo pic</span>
</li>
<li class="findme"><a class="mylink" href="https://yahoo.com">yahoo</a></li>
</ul>
</div>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
