Manipulate CSS Before Selector With JQuery
I'm trying to access the CSS :before and :after selectors with jQuery. I have tried a few methods, but it seems that the CSS selectors can't be seen by the DOM. What I'm trying to
Solution 1:
(function($) {
jQuery.fn.extend({
getPseudo: function(pseudo, prop) {
var props = window.getComputedStyle(
$(this.selector).get(0), pseudo
).getPropertyValue(prop);
return String(props);
},
setPseudo: function(_pseudo, _prop, newprop) {
var elem = $(this);
var s = $("style");
var p = elem.getPseudo(_pseudo, _prop);
console.log(p)
var r = p !== "" ? new RegExp(p) : false;
var selector = $.map(elem, function(val, key) {
return [val.tagName, val.id
? "#" + val.id : null, val.className ? "." + val.className
: null]
});
var _setProp = "\n" + selector.join("")
.concat(_pseudo)
.concat("{")
.concat(_prop + ":")
.concat(newprop + "};");
((!!r ? r.test($(s).text()) : r) ? $(s).text(function(index, prop) {
return prop.replace(r, newprop)
}) : $(s).append(_setProp));
return this
}
})
})(jQuery);
$(".className").setPseudo(":before", "background", "blue");
.className:before {
background: red;
content: "123";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="className">abc</div>
Solution 2:
You can't change the style of pseudo elements with javascript, but you could add a <span>
inside of your .className
and then target that.
$('.className span').css('background-color', bgColor);
Post a Comment for "Manipulate CSS Before Selector With JQuery"