Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add pseudo classes to elements using jQuery?

In CSS, when you hover your mouse over an element, you can specify views for it using the :hover pseudo class:

.element_class_name:hover {     /* stuff here */ } 

How can you use jquery to add or "turn on" this pseudo class? Typically in jQuery if you want to add a class you would do:

$(this).addClass("class_name"); 

I have tried "hover" but this literally adds a class named "hover" to the element.

If anyone knows what to write, please let me know! Thanks!

like image 843
jay Avatar asked Oct 05 '12 06:10

jay


People also ask

How do I target a pseudo-element in JavaScript?

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS. Show activity on this post. We can also rely on custom properties (aka CSS variables) in order to manipulate pseudo-element.

What are the pseudo-classes associated with a element?

What is a pseudo-class? A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer.

What are pseudo-classes and pseudo elements with example?

Basically a pseudo-class is a selector that assists in the selection of something that cannot be expressed by a simple selector, for example :hover . A pseudo-element however allows us to create items that do not normally exist in the document tree, for example ``::after`.


2 Answers

You can't force a certain pseudo-class to apply using jQuery. That's not how pseudo-classes (especially dynamic pseudo-classes) work, since they're designed to select based on information that cannot be expressed via the DOM (spec).

You have to specify another class to use, then add that class using jQuery instead. Something like this:

.element_class_name:hover, .element_class_name.jqhover {     /* stuff here */ }  $(this).addClass("jqhover"); 

Alternatively you could hunt for the .element_class_name:hover rule and add that class using jQuery itself, without hardcoding it into your stylesheet. It's the same principle, though.

like image 107
BoltClock Avatar answered Sep 28 '22 18:09

BoltClock


I think there is no way to do that with jQuery or javascript.

You can find the same answer in these two questions:

  1. setting-css-pseudo-class-rules-from-javascript
  2. css-pseudo-classes-with-jquery
like image 26
chanjarster Avatar answered Sep 28 '22 16:09

chanjarster