There are several ways, by pure javascript the ideal is that you use the reference of your element and in it use the method removeAttribute
, examples:
document.querySelector('#minhaAncora').removeAttribute('href');
document.getElementById('minhaAncora').removeAttribute('href');
But when you remove this property from the anchor, this anchor ceases to function as anchor, losing the characteristics of the pseudo selectors :hover
, :active
, :focus
and :visited
what can be an unwanted behavior.
In this case you can replace the attribute value with a hash, example:
document.querySelector('#minhaAncora').setAttribute('href', '#');
However this can influence the browser scroll depending on the elements and page size, so another solution is to put in place a script that does nothing, example:
document.querySelector('#minhaAncora').setAttribute('href', 'javascript: ');
It will maintain anchor properties but will do nothing when clicked. Because the browser interprets this as an "evaluation" of code during the click event, but since there is no code, it ignores the command.
Tip for those who use jQuery would look like this:
$('#minhaAncora').attr('href', 'javascript: '); // modifica pra não fazer nada
$('#minhaAncora').attr('href', '#'); // faz o scroll mover-se para inicio do documento, mas não muda de página
$('#minhaAncora').removeAttr('href'); // remove o atributo da tag
If you do not want to remove, you can use the pointer-event
CSS to invalidate the use of cursor events in the tag, but this does not remove the link that can still be accessible with Focus (use tab) then enter, only modern browsers have support.
If you don’t want to remove the attribute, but just remove their event, you can prevent the default action with the following code:
document.querySelector('#minhaAncora').addEventListener('click', function (e) {
e.preventDefault();
});
// Compatível com todos browsers modernos, IE antigos precisa retornar false
// e a forma de adicionar eventos é por outro método.
// No caso use o jQuery:
$('#minhaAncora').on('click', function (e) {
e.preventDefault();
});
Interesting solution, too. Congratulations!
– Dennis Braga
can you tell me if it’s possible to reverse this process and if so, how?
– Dennis Braga
@Dennisbraga, yes, it’s easy, just use
$('#minhaID').css("pointer-events", "");
- Example: http://jsfiddle.net/Tn52U/1/– Sergio
Edit your answer and add that. It’s really cool that you can remove the link without losing information and power, simply via CSS, reactivate it. : D
– Dennis Braga
@Dennisbraga, done! good idea.
– Sergio
This css solution is supported by older browsers?
– Joao Paulo
@No. I added a link to give this information.
– Sergio
Just be careful when using Pointer-Events, as it only works on 3 browsers... as per the specification: http://caniuse.com/#search=Pointer%20events
– picossi