Reputation: 2110
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.
Upvotes: 0
Views: 11419
Reputation: 87233
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');
});
Upvotes: 3
Reputation: 19382
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
Upvotes: 1
Reputation: 32327
Is it possible that when you don't want the href you do something like this
$($.find("a")).attr("href", "#")
Upvotes: 0
Reputation: 33238
You can use removeAttr():
$('a').removeAttr('href');
<script src="https://ajax.googleapis.com/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
Upvotes: 6