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 the images with a link with the same href attribute of a.title.
And I coded up something like this in jQuery, but the result gives to me is only the href of the first 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>
This should work (if you fix your HTML†).
(could also use
li:has(a.title)instead ofli:has(h3)…)If your markup is fixed like that, you could also retrieve the value with:
†:
aelements need a closing tag.aelement needs thetitleclass.