Wrap each image in an article with the "href" title of the parent link
I have this code:
<ul>
<li>
<h3><a class="title" href="page1.html">Post Title</a></h3>
<ul>
<li>
<img src="imageOne.png" alt="" />
<p>Some text.</p>
</li>
</ul>
</li>
<li>
<h3><a class="title" href="page2.html">Post Title</a></h3>
<ul>
<li>
<img src="imageTwo.png" alt="" />
<p>Some text.</p>
</li>
</ul>
</li>
<!-- [...] -->
</ul>What I want to do in JS / jQuery: wrap all images with a link with the same attribute hrefin a.title.
And I encoded something like this in jQuery, but the result gives me only the hreffirst a.title:
$("ul li ul li img").each(function() {
$(this).wrap("<a href='" + $("ul li a.title").attr("href") + "'> </a>");
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<h3><a class="title" href="page1.html">Post Title</a></h3>
<ul>
<li>
<img src="imageOne.png" alt="" />
<p>Some text.</p>
</li>
</ul>
</li>
<li>
<h3><a class="title" href="page2.html">Post Title</a></h3>
<ul>
<li>
<img src="imageTwo.png" alt="" />
<p>Some text.</p>
</li>
</ul>
</li>
<!-- [...] -->
</ul>+3
5 answers
This should work (if you fix your HTML † ).
$("ul li ul li img").each(function(){
$(this).wrap("<a href='"+ $(this).closest("li:has(h3)").find('a.title').attr("href") + "'> </a>");
});
(can also be used li:has(a.title)instead li:has(h3)...)
If your markup is fixed the same way, you can also get the value with:
$(this).parents('li').find('a.title').attr('href')
†:
- Elements
aneed a private tag. atitle.
+7
HTML ( "" "a" )
<ul>
<li class="article">
<h3><a class="title" href="page1.html">Post Title 1</a></h3>
<ul>
<li>
<img src="image.png" alt=""/>
<p>Some text 1</p>
</li>
</ul>
</li>
<li class="article">
<h3><a class="title" href="page2.html">Post Title 2</a></h3>
<ul>
<li>
<img src="image.png" alt=""/>
<p>Some text 2</p>
</li>
</ul>
</li>
JS
$(document).ready(function() {
$(".article").each(function(){
var img = $(this).find('img');
var title = $(this).find('.title');
img.wrap("<a href='"+ title.attr("href") + "'></a>");
});
});
NB: , " "
0