faressoft
faressoft

Reputation: 19651

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

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

Upvotes: 1

Views: 2792

Answers (3)

Joel Etherton
Joel Etherton

Reputation: 37533

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 = "#";
}

Upvotes: 2

Peter Boughton
Peter Boughton

Reputation: 112170

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).

Upvotes: 6

stusmith
stusmith

Reputation: 14103

Using jQuery:

$('a').attr('href', '#');

Upvotes: 3

Related Questions