There are several ways, by pure javascript, you should ideally use the reference of your element and use the removeAttribute
method, examples:
document.querySelector('#minhaAncora').removeAttribute('href');
document.getElementById('minhaAncora').removeAttribute('href');
But when you remove this property from the anchor, this anchor no longer works as anchor, losing the characteristics of the :hover
, :active
, :focus
and :visited
pseudo selectors which may be unwanted behavior. / p>
In this case you can replace the value of the attribute with a hash, eg
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 a script that does nothing, for example:
document.querySelector('#minhaAncora').setAttribute('href', 'javascript: ');
It will keep the properties of the anchor but will not do anything when clicked. Because the browser interprets this as a code "evaluation" during the click event, but since there is no code, it ignores the command.
Tip for anyone using 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% css% to invalidate the use of cursor events in the tag, however this does not remove the link that can still be accessible with focus (use tab) then enter only Modern browsers are supported.
If you do not want to remove the attribute but just remove the event from them, 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();
});