Question

Why can't I change the CSS of an a tag with jquery? For instance,

html,

<a href="#">1</a>
<a href="">2</a>
<a href="http://website.com/#/home/about/">3</a>
<a href="http://website.com/home/about/">4</a>

link 1 and 2 are not clickable so I want to remove the pointer cursor.

jquery,

$("a").click(function(e){
    if($(this).attr("href") == "#" || $(this).attr("href") == "") {
        alert("this is non-clickable");
        $(this).css({cursor:"default"});
        e.preventDefault();   
    }
    else{
        alert($(this).attr("href"));
        $(this).css({cursor:"pointer"});
        e.preventDefault();   
    }
});

is it possible?

jsfiddle

Was it helpful?

Solution

If you want you can simply do this with the CSS

a[href="\#"], a[href=""] {
    cursor: default;
}
/* I've used an element[attr] selector here which will select all a tags 
   with this combination, if you want to target specific a tags, 
   wrap them in an element with a class and you can than refer as 
   .class a[href]... */

Demo

If you want to disable the links, you can achieve that too using CSS pointer-events: none; property

Demo 2 (Will help you if JS is disabled, this won't alert the message, but it will help you to disable the event which you are trying to do)

OTHER TIPS

Your error is in your jquery css. You need quotes round css your js should look like this:

$("a").click(function(e){
    if($(this).attr("href") == "#" || $(this).attr("href") == "") {
        alert("this is non-clickable");
        $(this).css({'cursor' :"default"});
        e.preventDefault();   
    }
    else{
        alert($(this).attr("href"));
        $(this).css({'cursor':"pointer"});
        e.preventDefault();   
    }
});

Also you could use addClass method then in the css have a style for no href

try to change the line

form

$(this).css({cursor:"default"});

to

$(this).css('cursor','default');

let me know if you face any problem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top