简体   繁体   中英

Get an anchor text value among multiple anchor's with same href

My html is

<a id='_requestOne' href='#applynow'> apply one </a>

<a id='_requestTwo' href='#applynow'> apply two </a>

<a href='#applynow'> apply three </a>

I want to change the anchor text for the second one alone. so I implemented in script as

$("a[href='#applynow']").text("request call");

Its changing all the three tags, so I tried as

$("#_requestTwo a[href='#applynow']").text("request call");

But its not working. Can anyone give me a solution that how could I declare both id & href in same call.

Thanks in advance.

What you can do is target the second Item of the jQuery Object:

$( $("a[href='#applynow']")[1] ).text('request call') //starts counting at 0

I do not advise on this, it makes the code less maintenable if the html markup changes. You have an ID, so use that instead.

$("#_requestTwo").text('request call')

PS:

The reason why your second try doesn't work is because you had an error in the selector:

$("#_requestTwo a[href='#applynow']") 
//should be 
$("a[href='#applynow']#_requestTwo") 

First select anchors with href then specify with ID or select directly by ID because ID should be unique:

 $("a[href='#applynow']#_requestTwo").text("request call");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id='_requestOne' href='#applynow'> apply one </a> <a id='_requestTwo' href='#applynow'> apply two </a> <a href='#applynow'> apply three </a>


Always select elements from low to high specificity like:

$("tagname.class");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM