Selecting and Manipulating CSS Pseudo-Elements Such as ::Before and ::After Using JavaScript (Or Jquery)

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){
$(this).attr('data-content','bar');
});

In CSS:

span:after {
content: attr(data-content) ' any other text you may want';
}

If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){
$(this).addClass('change').attr('data-content','bar');
});

In CSS:

span.change:after {
content: attr(data-content) ' any other text you may want';
}

modify pseudo select :after in javascript

If that style comes from a CSS file, you'll have to search for it in document.styleSheets, which will be messy.

If you are open to dynamically creating a <style> element containing that CSS instead, you can modify it programmatically.

var slidingTagLiAfterStyle = document.createElement("style");
slidingTagLiAfterStyle.innerHTML =
".slidingTag li:after {
content: '';
z-index: 3;
height: 6px;
}";
document.head.appendChild(slidingTagLiAfterStyle);

...

slidingTagLiAfterStyle.innerHTML = slidingTagLiAfterStyle.innerHTML.replace(/height: [0-9]+px/, "height: 12px"); // or whatever you want to set it to

Changing pseudo-element style from javascript

Since pseudo-elements do not exist in the DOM, they cannot be accessed in Javascript.
The workaround is to create a <span> instead of using :before and the same logic has to be applied.

JQuery select pseudo-element :after

It's not possible to bind directly to pseudo-elements, since those are not part of the DOM, but the desired effect can be approximated by binding to a parent element and testing for an offset related to the element that the :after acts upon:

The following renders as ELEMENT++, where clicking on "ELEMENT" and "++" each triggers different behavior:

<span>ELEMENT</span>
span::after {
content: '++';
position: absolute;
}

span.c1 {
background: yellow;
}

span.c2::after {
background: orange;
}
const span = document.querySelector('span');

span.addEventListener('click', function (e) {
if (e.offsetX > span.offsetWidth) {
span.className = 'c2';
} else {
span.className = 'c1';
}
});

Interactive: http://jsfiddle.net/wC2p7/1/

Use of Pseudo-Element ::before in JavaScript

No, you cannot access :before or :after from javascript, because they are not a part of the DOM. However you can still achieve your goal by using CSS classes. Example:

<script>
document.getElementById('abc').className += "minus";
</script>

<style>
#all-address:before {
display: none;
}
#all-address.minus:before {
display: block;
}
</style>


Related Topics



Leave a reply



Submit