views:

65

answers:

3

how to set all links(href) in the page to "#" with javascript

+2  A: 

Use the getElementsByTagName() method to get the tags, then loop through them to set the property.

var links = document.getElementsByTagName("a");

for (var link in links)
{
    links[link].href = "#";
}

EDIT: To satisfy a non "foreach" method.

var links = document.getElementsByTagName("a");

for(i=0;i<links.length;i++) 
{
    links[i].href = "#";
}
Joel Etherton
`for..in` is bad practice for [pseudo]arrays.
strager
@strager - documentation? reason?
Joel Etherton
Don't use `for( i in ... )` to loop over array-like objects, e.g. NodeLists.
J-P
Also, your code is wrong: the inner part of the loop should read `links[link].href`, not `link.href`. `link` is the index.
strager
@Joel, a) it's slow (Really slow) b) It'll loop over any items added to the prototype (which isn't what you want).
J-P
See http://jsperf.com/loop-test
J-P
@Joel Etherton, See [Why is using "for ...in" with array iteration such a bad idea?](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays)
strager
@strager, @J-P thanks for the references. I will read. @strager, no var link creates the reference not an index (this array is not associative). I've used similar code to generate elements.
Joel Etherton
@Joel Etherton, Blasphemy! `link` is the index. I just checked.
strager
@strager - I stand corrected.
Joel Etherton
This is the correct answer. Thanks for helping.
faressoft
You're not declaring `i` and you should *cache* the `length` of the array in another var.
J-P
+3  A: 

Using jQuery:

$('a').attr('href', '#');
stusmith
+6  A: 

DON'T CHANGE HREF TO #

Set the onclick function to return false instead.

This will have the same effect, whilst allowing greater usability.

Here's a quick example (using jQuery, but works with anything):

jQuery('a').click( doStuff );

function doStuff()
{
    // ...function body...

    return false;
}

This works because the value you return from an onX event function determines whether that event continues firing or stops. Return true to allow it to continue or false to stop it.

With onclick this means the click is stopped (so the link isn't followed) - however it still allows people to interact with the link via middle and right click (e.g. opening in new tab, adding to bookmarks, and so on)

For another example, with onkeypress you can return false to prevent the character typed from being added to an input control (for example, you could mimic the HTML5 input="numeric" control by having an onkeypress that returned false for any non-numeric characters).

Peter Boughton
I don't want jQuery
faressoft
Then don't use jQuery. The concept of returning true/false is core JavaScript. I don't bother remembering the two or three different ways of binding methods, so I used jQuery for simplicitly.
Peter Boughton