Skip to content Skip to sidebar Skip to footer

Cross-browser Change An A Tags' Href

it seems I can not find document.getElementById().href in the Javascript reference, there are a lot of sites saying to use this to change the href of a link. Is this safe? Will it

Solution 1:

You can't find it in any reference, as it's not a single construct, it's the combination of two.

Use the document.getElementById method to get a specific element, and if that element is an anchor tag, you can use the href property to set the URL.

Both are specified in the DOM level 1 specification, so they are safe to use in any browser that isn't more than a decade old, and most that are a bit older too.

Solution 2:

Solution 3:

I am fairly sure it is "safe" nothing bad will happen. It works in all browser I have tested it in, and is the standard in which JavaScript changes the values of elements attributes.

Solution 4:

I have asked a similar question here: Retrieving HTML attribute values "the DOM 0 way"

Check out the answers. The conclusion is that the attributes src, href and style are not safe and a JavaScript library is recommended.

For the href attribute, I recommend jQuerys attr() method.

// retrieve the anchor by IDvar anchor = $('#anchorID');

// get the href attributevar href = anchor.attr('href');

// set the href attribute
anchor.attr('href', 'http://www.google.com');

Post a Comment for "Cross-browser Change An A Tags' Href"