how to set all links(href) in the page to "#" with javascript
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 = "#";
}
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).