Home > Web Front-end > CSS Tutorial > Can jQuery Select CSS Pseudo-elements Like :before and :after?

Can jQuery Select CSS Pseudo-elements Like :before and :after?

Mary-Kate Olsen
Release: 2024-11-29 10:39:14
Original
576 people have browsed it

Can jQuery Select CSS Pseudo-elements Like :before and :after?

Accessing Pseudo-Elements through jQuery

While working on a previous question, we explored the challenge of selecting pseudo-elements based on the effects of CSS rules. Let's explore an alternative approach using jQuery selectors.

Background Properties

Consider the following default CSS properties:

.commentarea .author:before {
    background-image: url(http://...);
    background-position: -9999px -9999px;
    /* ... */
}
Copy after login

These properties are then modified selectively:

.author[href$="gbacon"]:before /* ... */ {
  content: "";
  background-position: 0 -140px
}
Copy after login

jQuery Selectors

To select pseudo-elements with default background positions, basic selectors like this will not work:

GM_log("size = " + $(".commentarea .author:before").size());
Copy after login

Other attempts, such as using .siblings(), also fail to produce desired results.

Limitations of Pseudo-Element Selectors

It's important to note that :before and :after are not valid jQuery selectors. They serve a specific purpose:

  • :before inserts content before the selected element
  • :after inserts content after the selected element

Example Usage

The following HTML and CSS demonstrate how :before and :after work:

<span class='a'>
    Outer
    <span class='b'>
        Inner
    </span>
</span>
Copy after login
.a .b:before {
    content: "|Inserted using :before|";
}

.a {
    color: blue;
}

.b {
    color: red;
}
Copy after login

In this example, text is prepended to the inner span using :before.

Alternatives

Since :before is not a valid jQuery selector, alternative approaches are necessary. One option is to use external jQuery plugins like jQueryRule to extract the original rule.

Please note that accessing style properties of pseudo-elements with jQuery can be challenging. Consider carefully whether there are alternative approaches that may meet your needs more effectively.

The above is the detailed content of Can jQuery Select CSS Pseudo-elements Like :before and :after?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template