Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each link where href equals myValue

Tags:

html

jquery

Why is the following not changing the text to it worked?

//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 it doesn't seem to pick up the href value.attr but I may be getting it all wrong can someone please make sure I have the above correctly done?

like image 360
Anicho Avatar asked Sep 17 '12 09:09

Anicho


People also ask

What is the <a href> attribute?

The HTML a href Attribute Explained with Examples The <a href> attribute refers to a destination provided by a link. The a (anchor) tag is dead without the <href> attribute. How to use the <a href> tag

How to use the <a href> tag?

How to use the <a href> tag Sometimes in your workflow, you don’t want a live link or you won’t know the link destination yet. In this case, it’s useful to set the href attribute to "#" to create a dead link. The href attribute can be used to link to local files or files on the internet.

What are hreflang attributes and how to add them?

Hreflang attributes indicate the relationship between pages in different languages on your website to search engines. If your website targets a multinational audience, you'll need to add hreflang attributes. When the Google bots try to scan your website, they will likely stop move on if they find multiple broken links.

What happens if I reference more than one language in hreflang?

This warning triggers when one or more URLs are referenced for more than one language in hreflang annotations. For example: Each piece of content should only serve one language or language-location. Having two or more contradicting references will confuse search engines, and they may end up ignoring both hreflang attributes.


1 Answers

i is the index of the element, you want the element and should use should use something like:

// 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>

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

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

like image 71
Anil Avatar answered Oct 01 '22 06:10

Anil