Is it possible to hide the href
without hiding the whole anchor tag?
<a href="somelinks">Click Me</a>
The reason I need this is because I'd need to hide and show it based on desktop and mobile view controlled by JS.
Something like $('a').attr('href').hide();
won't work
Edit:
I need to 'hide' the href so I can 'show' it where I need to. Removing the href
will not restore it.
Is it possible to hide the href
without hiding the whole anchor tag?
<a href="somelinks">Click Me</a>
The reason I need this is because I'd need to hide and show it based on desktop and mobile view controlled by JS.
Something like $('a').attr('href').hide();
won't work
Edit:
I need to 'hide' the href so I can 'show' it where I need to. Removing the href
will not restore it.
$('a').on('click',function(){return false;});
should work
– R Lam
Commented
May 27, 2015 at 10:55
You can use removeAttr():
$('a').removeAttr('href');
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="somelinks">Click Me</a>
Description: Remove an attribute from each element in the set of matched elements
If you want to hide the href
but still want it to redirect when clicked, use this.
Get the URL and put it in data
attribute. Then remove the href
attribute.
$('a').each(function() {
$(this).data('href', $(this).attr('href')).removeAttr('href');
});
When clicked on anchor
, get the URL from data
attribute and redirect.
$('a').on('click', function() {
window.location.href = $(this).data('href');
});
But what if You want to restore href? From where will You get it?
<div class="some-container">
<a href="somelinks">Click Me</a>
<a href="somelinks2">Click Me</a>
</div>
function hideHrefs(selector) {
$(selector).each(function(){
var $this = $(this);
var href = $this.attr('href');
$this.attr('href', '').data('href', href);
});
}
function restoreHref($element) {
var href = $element.data('href');
$element.attr('href', href);
}
hideHrefs('.some-container a'); // hides all hrefs from links in container element
restoreHref($('.some-container a:first')); // restores href for dedicated element
Is it possible that when you don't want the href you do something like this
$($.find("a")).attr("href", "#")