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=""> a1</a>
<a href="" rel="nofollow" > a2</a>
<a href="">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
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."> a1</a>
<a href="https://www.abc." rel="nofollow" > a2</a>
<a href="https://www.abc.">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
Share Improve this question edited Oct 17, 2013 at 7:18 user2142786 asked Oct 17, 2013 at 6:31 user2142786user2142786 1,48210 gold badges43 silver badges79 bronze badges 2-
rel="nofollow"
you are missing quotes . – Tushar Gupta - curioustushar Commented Oct 17, 2013 at 6:32 - Should the src actually be an href? – Brian Wigginton Commented Oct 17, 2013 at 6:42
5 Answers
Reset to default 3$('a').each(function(){
if(this.innerHTML == 'a1' || this.innerHTML == 'a2'){
$(this).attr('rel','nofollow');
}
});
updated after op's cpmment
DEMO
$('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."> a1</a>
to
<a href="https://www.abc."> a1</a>
it's not src
it's href
tri this:
var A=document.getElementsByTagName("a");
for(var i=0;i< A.length;i++)
{
if(A[i]['rel']!="")
{
A[i].setAttribute("rel","Something");
}
}
$("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
}
$(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
}
);
});
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');
}
});