0

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.

Nima
  • 2,100
  • 2
  • 23
  • 32

4 Answers4

6

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

Alex Char
  • 32,879
  • 9
  • 49
  • 70
3

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');
});
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

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
num8er
  • 18,604
  • 3
  • 43
  • 57
0

Is it possible that when you don't want the href you do something like this

$($.find("a")).attr("href", "#")
Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55
  • What is `$($.find("a"))` ? – Tushar May 27 '15 at 10:45
  • $.find("a") will get you all the anchor tags you can give your specific selector here. [More](https://api.jquery.com/find/) $($.find("a")).attr("href", "#") //to all the anchors tags returned by find make the href as "#" – Cyril Cherian May 27 '15 at 10:49