Get href attribute of the closing tag of the link

Having a bit of trouble with this. I need to use Jquery / JS to find the HREF attribute of a link anchor tag:

<a href="something.html"><img src="img1.jpg" class="active"></a>

I want to target img to a class and find the value of the 1st preceding href attribute.

$("img.active").somethingAwesome().attr("href");

Please show me something peculiar () ... help?

+3
source share
4 answers

$("img.active").parent("a").attr("href")will receive the attribute of the direct parent href, considering it to be a binding. If there is any depth of block content between the image and the anchor, use instead $("img.active").closest("a").attr("href").

+6
source

.parent() - that’s all you need!

$("img.active").parent().attr("href");

Here is the documentation :)

According to Kyle's comment, and trying to do something as reliable as possible, you can try:

$("img.active").closest('a[href]').attr("href");

, html :

<a href="something.html">
    <a name="anchor">
        <img src="img1.jpg" class="active">
    </a>
</a>

, :)

+3

$ ("img.active") closest ("a") atr ("HREF"); ..

0
source
$("img.active").closest('a').attr("href");
0
source

Source: https://habr.com/ru/post/1796462/


All Articles