For each link where href is equal to myValue

Why didn't the following text changes work?

//JAVASCRIPT/JQUERY: $('a').each(function(i) { if($(i).attr("href") == "mywebsite.co.uk") { $(i).innerHTML = "It Worked!"; } }); //HTML: <a href="mywebsite.co.uk"></a> 

Debugging doesn't seem to pick up the href value.attr value, but I could be wrong, can someone please make sure I did it right?

+7
source share
5 answers

i is the index of the element, you want the element to use it, for example:

 // The first argument is the index, the second is the element $('a').each(function(index, element) { if($(element).attr("href") == "mywebsite.co.uk") { $(element).html("It Worked!"); // Change this to .html() } console.log('Index is:'+index+', Element is'+element); });​ <a href="mywebsite.co.uk"></a> 

In addition, I changed .innerHtml() to .html("content in here") . To update the HTML inside the returned <a></a> (element) tag.

Check the JSFiddle . http://jsfiddle.net/2scug/1/

+11
source

It may be shorter to write it as:

 $('a[href="mywebsite.co.uk"]').each(function() { $(this).html("It Worked!"); }); 

There is also a reason jQuery has an html () function. It cleans up all possible memory leaks and then uses innerHTML inside to set the desired value; -)

+5
source

Fixed:

 //JAVASCRIPT/JQUERY: $('a').each(function(i) { if($(this).attr("href") == "mywebsite.co.uk") { $(this).html("It Worked!"); } }); 

jsFiddle: http://jsfiddle.net/kAWdy/

+5
source

Try:

 $('a').each(function(i,v) { console.log(); if($(v).attr("href") == "mywebsite.co.uk") { $(v).html('It worked!'); } }); 
+4
source

Here I made full bins for the above problem. you can check the demo link here

Demo http://codebins.com/bin/4ldqp75/1/For%20each%20link%20where%20href%20equal

 <a href="mywebsite.com"> </a> <a href="mywebsite.co.uk"> </a> <a href="mywebsite.us"> </a> <a href="mywebsite.in"> </a> <input type="button" id="btn1" value="Get Text"/> 

jQuery:

 $(function() { $("#btn1").click(function() { $("a").each(function() { if ($(this).attr('href').trim() == "mywebsite.co.uk") { $(this).html("UK Website Link"); } else { $(this).html("Website Link"); } }); }); }); 

CSS

 a{ display:block; } input[type=button]{ margin-top:10px; } 

Demo http://codebins.com/bin/4ldqp75/1/For%20each%20link%20where%20href%20equal

+1
source

All Articles