Find all link in a div element and disable them all
Asked Answered
F

4

9

Assume that I have some HTML elements like these :

<div id="content_div">
    <span><a href="some_link">Click me</a></span>
    <div> Hello everybody. Click <a href="some_link_else">me</a> to do something else</div>

    <a href="3rd_link"> Oops </a>
</div>

All that I need is get all "a" tags in the #content_div and disable all of them (I don't want user to click on them). How could I do that in Jquery?

Fosque answered 19/6, 2013 at 8:54 Comment(1)
What does you mean with "disable" links?Mcfarlin
P
13

Try this:

 $("#content_div a").click(function(e) {
   e.preventDefault();
 });
Procambium answered 19/6, 2013 at 8:57 Comment(0)
S
17

I would rely less on jQuery as it might be disabled by the user, so if you want a CSS solution, you can do it like

#content_div {
   pointer-events: none;
   cursor: default;
}

Demo

Edit: To be precise, use this declaration #content_div a

Subvert answered 19/6, 2013 at 8:59 Comment(1)
Doesn't work in IE before 11, but it's a great solution if that's acceptable!Carmarthenshire
P
13

Try this:

 $("#content_div a").click(function(e) {
   e.preventDefault();
 });
Procambium answered 19/6, 2013 at 8:57 Comment(0)
P
4
$("#content_div a").css({"color":"#888888", cursor: "default"}).click(function(e){
   e.preventDefault();
});

Working Example http://jsfiddle.net/P4Fqq/

Pentobarbital answered 19/6, 2013 at 8:57 Comment(2)
Thank you very much. I can't accept 2 answer at once, so I upvote your answer instead.Balata
@quangtruong1985 See the updated code which changes the cursor to indicate it cannot be clicked.Pentobarbital
X
3

There are two ways here:

1) $('#content a').css({"pointer-events":"none"});

2) $('#content a').click(function(e){ e.preventDefault(); });

Xerophthalmia answered 22/8, 2015 at 10:32 Comment(1)
How can you enable the events after this?Erastian

© 2022 - 2024 — McMap. All rights reserved.