Reputation: 755
I want to add target="_blank"
for only the <a>
element where the last part of href
is page2.aspx
. How I can do that using jQuery? I tried this:
$j("a[href='page2.aspx']").attr('target', '_blank'); // not sure if it works?
<a href="/en-gb/mypage/Pages/page1.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page2.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page3.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page4.aspx">My Site</a>
I could not access <a>
like below because of variation(language) changes every time page renders.
$j("a[href='/en-gb/mypage/Pages/page2.aspx']").attr('target', '_blank');
How can I fix that?
Upvotes: 0
Views: 21
Reputation: 337590
You can use the Attribute ends with selector:
$j("a[href$='page2.aspx']").prop('target', '_blank');
$("a[href$='page2.aspx']").prop('target', '_blank');
// here's something that makes a visible difference so you
// can see the element is targeted properly
$("a[href$='page2.aspx']").css('color', '#C00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/en-gb/mypage/Pages/page1.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page2.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page3.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page4.aspx">My Site</a>
Upvotes: 2