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.
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';
}
Set CSS property in JavaScript?
Use element.style
:
var element = document.createElement('select');
element.style.width = "100px";
Changing CSS pseudo-element styles via JavaScript
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
Javascript set CSS :after styles
var addRule = (function(style){
var sheet = document.head.appendChild(style).sheet;
return function(selector, css){
var propText = Object.keys(css).map(function(p){
return p+":"+css[p]
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
}
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
A minimal implementation. You most likely would want to keep track of the rules you add so you can remove them. sheet.insertRule
returns the index of the new rule which you can use to get a reference to it for editing or removal.
Edit: added basic functionality to convert an object into a css property string for convenience.
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
Apply CSS dynamically with JavaScript
Using Jquery
Use the css() function to apply style to existing elements where you pass an object containing styles :
var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);
You can also apply one style at the time with :
$("#myId").css("border-color", "#FFFFFF");
Vanilla JS :
var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");
With Css :
You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.
in your css file you can have classes like
.myClass {
background-color: red;
}
.myOtherClass {
background-color: blue;
}
Again using jquery, to add or remove a class to an element, you can use
$("#myDiv").addClass('myClass');
or
$("#myDiv").removeClass('myClass');
Again, you can also do the same with vanilla JS:
document.getElementById("#myId").classList.add('myClass')
or
document.getElementById("#myId").classList.remove('myClass')
I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.
Dynamically styling pseudo-elements using jQuery or Javascript
May I suggest doing like this, where you dynamically create a style
element (with a unique id so you can access it over and over) and just update a rule repeatedly
Usage
loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');
Script
function loadStyle(css) {
var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
style.id = 'lastinbody';
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.querySelector('body').appendChild(style);
}
At this post of mine is a few more versions (which might be consider as a possible duplicate)
Related Topics
Why Does Getelementbyid Not Work on Elements Inside the Document Element
Find Selected Item in Datalist in HTML
Bootstrap 3 Accordion Collapse Does Not Work on Iphone
How to Find CSS Rules from an HTML Node via JavaScript
Using Media Queries to Only Include Js Files on Mobile
Fontawesome Fails to Load Fonts Locally and in Electron App
Determine the Width of a Dynamic CSS3 Multicolumn Div Width Fixed Column-Width
Make Webelement Visible via Selenium with Python with JavaScript
Canvas.Todataurl() Security Error the Operation Is Insecure
Center Flex Item in Container, When Surrounded by Other Flex Items
How to Set Active Class to Nav Menu from Twitter Bootstrap
Dynamically Changing Stylesheet Path Not Working in Ie and Firefox
How to Detect MAC Os Inverted Color Mode in JavaScript/Css
How to Make JavaScript Scrollintoview Smooth
Can Bootstrap (4) Be Integrated Along with Angular Material (2)