ProllyGeek
ProllyGeek

Reputation: 15836

jQuery $(this) pseudo selector

I have a link which I want to addClass on mouseover like following:

$("#navbarlarge").on("mouseover","a",function(){
                $(this).addClass("linkeffect");
})

The issue is that I also want to add a class to both ::before and ::after pseudo elements inside the link , tried this but doesn't work:

$(this).find("::before").addClass("beforeeffect");

how can i combine this selector with the pseudo element ?

Upvotes: 0

Views: 1820

Answers (2)

Billy
Billy

Reputation: 2448

Don't know if this will help, it does the same sort of thing and you can style the span as req'd. Been trying a while and the only other way I found that was any cop was adding a style direct to the head like in this thread SO Manipulating psuedo elems, I see from the comments there was a thread posted on this thread but it isn't showing up anymore so not sure if it's the same one.

$( "a" ).hover(
  function() {
    $( this ).append( $( "<span>>>></span>" ) );
    $( this ).prepend( $( "<span><<<</span>" ) );
  }, function() {
    $( this ).find( "span:last" ).remove();
    $( this ).find( "span:first" ).remove();
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">Hover Me</a>
<a href="#">Hover Me</a>

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You can't. Pseudo-elements are not selectable by JavaScript and therefore are not selectable by jQuery either.

Attach the class to the element itself, and apply CSS with #navbarlarge a... waitaminute.

Dispense with jQuery entirely.

#navbarlarge a:hover {
    /* styles to apply to hovered link */
}
#navbarlarge a:hover::before {
    /* styles to apply to hovered link before pseudo */
}
#navbarlarge a:hover::after {
    /* styles to apply to hovered link after pseudo */
}

Upvotes: 5

Related Questions