Reputation: 1482
i have a html page in which i have a number of anchor tags i want to add rel="no follow" attribute in anchor tag if it doesn't have it on the pages whose source is starting with hyper text transfer protocol request. some of the anchor have already rel attribute. how can i achieve it through
example:-
<html>
<body>
<p> Here we go</p>
<a href="https://www.abc.com"> a1</a>
<a href="https://www.abc.com" rel="nofollow" > a2</a>
<a href="https://www.abc.com">a3</a>
</body>
</html>
i want to add rel= no follow attribute on a1 and a2 on page load time how can i achieve this
Upvotes: 2
Views: 5134
Reputation: 2652
Updated Code
$('a:not([rel])[href^="http"]').attr('rel','nofollow')
Tushar Gupta provided a one liner that would find all http links and add rel
attributes, however it didn't account for links that already had rel
attributes.
Original Solution
// find all links that do not have a rel attribute
$('a:not([rel])').each(function() {
var $this = $(this),
href = $this.attr('href');
// check that the link starts with http[s]://
if(href && href.match(/https?:\/\//)) {
$this.attr('rel', 'nofollow');
}
});
Upvotes: 0
Reputation: 627
$(function () {// on page load time
$('a').each(function () {// check every a element
var text = $(this).html();// get the content
if (text.indexOf('a1') > 0 || text.indexOf('a2') > 0) {// find a1 and a2
$(this).attr('rel', 'no follow');// set the rel to no follow
}
);
});
Upvotes: 1
Reputation: 57095
$('a').each(function(){
if(this.innerHTML == 'a1' || this.innerHTML == 'a2'){
$(this).attr('rel','nofollow');
}
});
updated after op's cpmment
$('a[href^="http"]').attr('rel', 'nofollow'); // all links starting with http wil get rel attribute
^ attribute starts with selector
Change you HTML
<a src="https://www.abc.com"> a1</a>
to
<a href="https://www.abc.com"> a1</a>
it's not src
it's href
Upvotes: 3
Reputation: 36609
tri this:
var A=document.getElementsByTagName("a");
for(var i=0;i< A.length;i++)
{
if(A[i]['rel']!="")
{
A[i].setAttribute("rel","Something");
}
}
Upvotes: 1
Reputation: 10388
$("a:contains('a1'),a:contains('a2')").attr("rel","no follow");
reference contains-selector
updated
if($("a").attr("rel")=="no follow")
{
// do stuff
} else{// if not exist
//do your stuff
}
Upvotes: 1