javascript - How to select a tag via href in jquery -
i've search it. not same other's problem. want select <a>
tag using href
attribute. please see 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 href
attribute working fine. problem because dom traversal incorrect.
prev('li a')
not valid a
li
not sibling. need first use closest('li')
parent, prev()
, find('a')
, 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>
Comments
Post a Comment