how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button.

CSS code

.bigdiv{
    display:none;
    background-color:#efefef;
    box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4);
    border:2px solid #efefef;
    width:400px;
    height:300px;
    position:fixed;
    z-index:500;
    top:25%;
    left:25%;
    margin:0 auto;
    padding:20px;
    }
    .bigdiv:after {
        cursor:pointer;
        content:url('http://static.doers.lk/img/closebox.png');
        position: relative;
        right: -195px;
        top: -310px;
        z-index: 999;
    }

JQUERY

$(".left div").click(function () {

   $(".bigdiv").show("slow");


    $(".bigdiv").click(function () {
   $(".bigdiv").hide();
   }) ;  }) ;

HTML

<div class="left">
<div>intro text here</div><div></div><div></div>
</div>


<div class="bigdiv">some content</div>

I am looking for a way to target the :after elements using jQuery. Can anyone help with this?

Answer №1

Is it possible to target :after elements using jQuery?

Unfortunately, you cannot target generated pseudo-elements like :after with jQuery as they do not exist in the DOM.

This can be demonstrated with the following example:

CSS:

#bar:before {
  content: '[Before]'
}
#bar:after {
  content: '[After]'
}

HTML:

<body><div id="bar">Bar</div></body>

JavaScript:

(function() {

  var messages = [];
  var childElement;
  var newDiv;

  for (childElement = document.body.firstChild;
       childElement;
       childElement = childElement.nextSibling) {
    if (childElement.id) {
      messages.push("Child " + childElement.nodeName + "#" + childElement.id);
    }
    else {
      messages.push("Child " + childElement.nodeName);
    }
  }

  newDiv = document.createElement('div');
  newDiv.innerHTML = messages.join("<br>");
  document.body.appendChild(newDiv);

})();

The resulting page from the above code (assuming the script element is added to the body at the end) will display:

[Before]Bar[After]
Child DIV#bar
Child SCRIPT

Live Example | Source Code

It is clear that the generated pseudo-elements are not recognized within the DOM structure.

Answer №2

To retrieve the styles of a pseudo-element, you can utilize the getComputedStyle method, which is compatible with popular browsers such as IE9, IE10, Chrome, and Firefox. Unfortunately, I have not discovered a solution for achieving this in IE8.

var elementContent = getComputedStyle(this,':after').content;
var elementWidth = getComputedStyle(this,':after').width;

If you encounter an error stating that the function is undefined, consider using window.getComputedStyle instead.

Answer №3

Regrettably, jQuery (or JavaScript in general) does not allow you to target pseudo-elements.

Although jQuery's appendTo() function works similarly to CSS :after, it can serve as a substitute (albeit not as clean as a pure CSS solution).

For instance, instead of:

.bigdiv:after {
    cursor:pointer;
    content:url('http://static.doers.lk/img/closebox.png');
    position: relative;
    right: -195px;
    top: -310px;
    z-index: 999;
}

Try this approach:

CSS:

.bigdivAfter {
    cursor:pointer;
    position: relative;
    right: -195px;
    top: -310px;
    z-index: 999;
}

JS:

$("<div class=bigdivAfter><img src='http://static.doers.lk/img/closebox.png'></div>").appendTo(".bigdiv");

Then you can subsequently select the closebox image normally.

Answer №4

One way to incorporate a close button using jQuery is by dynamically adding the button and assigning a close event to it. Below is an example of how you can achieve this with jQuery and CSS:

CSS

.bigdivAfter {
    cursor:pointer;
    position: absolute;
    right: //customize as needed;
    top: //customize as needed;
    z-index: 999;
}

JQUERY

$(document).ready(function(){ 
$(".bigdiv").append('<img class="closeButton" src="http://static.doers.lk/img/closebox.png"/>');
$(".bigdiv .closeButton").click(function () {
   $(".bigdiv").hide();
   }) ;
$(".left div").click(function () {
   $(".bigdiv").show("slow");
}) ;

Alternatively, I recommend adding the image directly in the HTML instead of dynamically through jQuery for better performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data. The standard approach would be: this.resultData = response.data.results this.totalResults = response.data.total this.perPageResults = response.data.per_page However, ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Difficulty redirecting Ajax call to a timed-out, CAS-protected server

Our website's login system utilizes CAS for single sign-on. The CAS server is operating the JASIG CAS server at , while our web server runs on Rails at . Due to security reasons, the Rails server has a relatively short session timeout, resulting in o ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

eliminate item from list upon user clicking the button

Does anyone have any tips on how to effectively store and remove user-selected items from an object in JavaScript? I'm encountering an issue where only the first object in the array is being removed, and not the others. Any help would be appreciated! ...

Implementing Bootstrap 4 in an Angular 9 project without the use of JQuery

Currently, I am actively working on detaching all JQuery dependencies within my Angular project. Most of the dependencies stem from utilizing Bootstrap 4 components. Eliminating dropdowns and removing all instances of data-*** seemed to help in this proc ...

What is the correct method to properly encode JSON that may include HTML when displaying it in an HTML file?

After searching through numerous questions, none seem to address this specific scenario. app.get('/', function(req, res) { res.set('Content-Type', 'text/html'); res.send(`<html> <body> Hello, World! </body&g ...

Understanding the integration of sass with webpack in an Angular 4 project

Is it possible to reference a sass file instead of a css file directly in the index.html? If so, how does webpack compile the sass into a css file? Additionally, what is the most effective way to bundle the sass file when building the application? The ve ...

Send functions from the back-end Node to the front-end Angular

Introduction I am currently working on a project that involves verifying email addresses within an API in order to grant users access to a restricted section. To accomplish this, I have developed backend node code with three functions built using Node and ...

Adjusting the visibility of a div as you scroll

I'm trying to achieve a fade-in and fade-out effect on div elements when scrolling over them by adjusting their opacity. However, I'm facing difficulties in getting it to work properly. The issue lies in the fact that my div elements are positio ...

What are some strategies for disregarding global CSS styles?

I am facing an issue on my html page with a specific div structure. The <div id="container">/* lots of nested html with elements like div, ul, li etc */</div> is causing some trouble in my global css file called style.css. The style. ...

Update a table in Laravel view using AJAX with a table join operation

How can I access the "nombreSubdireccion" attribute from the "subdireccion" table when inserting/updating a new record in the "area" table using AJAX? Currently, I am only able to get it by reloading the page due to DB::table. I'm unsure of where to d ...

Apply the CSS style specifically to the initial row in the table

Is there a way to target the first row of a table with a different tr class using CSS? <div id="right"> <table> <tbody> <tr class="head"> <td >Date</td><td>Info</td><td>More</td> </tr> ...

React Warning: Every child component within a list must contain a distinct key property

Can you spot the issue in the following code snippet: <List> {sections.map(section => ( <> {section.header && <ListSubheader key={section.header}>{section.header}</ListSubheader>} {section.items ...

The AngularJS page on my website is currently stuck in the mobile version, and strangely, the Google Chrome console is

When browsing our AngularJS website in mobile view on Google Chrome, it gets stuck and becomes unresponsive. The developer console does not show any error messages during this time. To replicate the issue, switch to mobile view, click on the "All top compa ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

What is the best way to set the input type in AngularJS based on a variable?

Is there a way to dynamically set the input type based on another variable in AngularJS? I was considering using a directive that triggers from an onclick event to change the input type, but I'm not entirely sure. FIRST //loop <a class="orgTitle" ...