refer to first link of particular div
-
25-06-2021 - |
Question
I have following elements:
<div class="content" id="content_1" style="display: none; ">
<ul class="ad-thumb-list" style="width: 473px; ">
<li>
<a href="../images/portfolio/portfolio_1_1.png" class="ad-thumb0 ad-active">
<img src="../images/portfolio/thumbs/thumb_1_1.png" style="opacity: 1; ">
</a>
</li>
<li>
<a href="../images/portfolio/portfolio_1_2.png" class="ad-thumb0">
<img src="../images/portfolio/thumbs/thumb_1_1.png" style="opacity: 1; ">
</a>
</li>
<li>
<a href="../images/portfolio/portfolio_1_3.png" class="ad-thumb0">
<img src="../images/portfolio/thumbs/thumb_1_1.png" style="opacity: 1; ">
</a>
</li>
</ul>
</div>
I need to get href attribute of first link <a>
inside <ul> <li>
I have several this kind of divs, as you can see it has id='content_1', so others will have id='content_2'... and so on.
How can I get href of first a in first li of a called div with jQuery?
Solution
$('#content_1 li:first a').attr('href');
if you have many divs, then:
$('.content').each( function() {
$(this).find('li:first a').attr('href');
});
OTHER TIPS
The XPath to the a
of interest would be:
//div[@id="content_1"]/ul/li[1]/a
Which means, anywhere below the root of the document find a div
with the specified id
. Under that, find a ul
and get its first li
. Inside that, there is an a
.
How you actually achieve that in your case depends on what you're working with (client-side JS? one of the frameworks? web-scraping script?).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow