I've already search about it. But it is not the same as the other's problem. What I want is to select a <a>
tag using href
attribute. Please see my code below:
<div class="jump-to">
<ul>
<li>No a</li>
<li class="with-a">
<a href="hello1">Has a</a>
</li>
<li class="with-a">
<a href="hello8">Has a</a>
</li>
<li class="with-a">
<a href="hello10">Has a</a>
</li>
</ul>
</div>
var current_anchor = window.location.href;
var left_anchor = $(".jump-to ul li.with-a a[href="+ current_anchor +"]").prev("li a").attr("href");
alert(left_anchor);
The selection via the href
attribute is working fine. The problem is because your DOM traversal is incorrect.
prev('li a')
is not valid from the a
as the li
is not a sibling. You need to first use closest('li')
to get the parent, then prev()
, then find('a')
, like this:
var current_anchor = 'http://localhost/myproject/hello8'; var left_anchor = $('.jump-to ul li.with-a a[href="' + current_anchor + '"]').closest('li').prev('li').find('a').attr('href'); console.log(left_anchor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="jump-to"> <ul> <li>No a</li> <li class="with-a"> <a href="http://localhost/myproject/hello1">Has a</a> </li> <li class="with-a"> <a href="http://localhost/myproject/hello8">Has a</a> </li> <li class="with-a"> <a href="http://localhost/myproject/hello10">Has a</a> </li> </ul> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.