Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify pseudo select :after in javascript [duplicate]

I have defined a css like

.slidingTag li:after {
  content: '';
  z-index: 3;
  height: 6px;
}

I want to change the height attribute dynamically from JS. I can get the property using

window.getComputedStyle(document.querySelector('.slidingTag'), 'li:after').getPropertyValue('height')

But I do not know how to change the height attribute. I tried to use setProperty but it seems there is no such function available for pseudo-classes. Any ideas let me know.

like image 555
user596502 Avatar asked Mar 25 '15 15:03

user596502


People also ask

How do you change pseudo element?

In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.

Can you combine pseudo selectors?

If you're talking about pseudo-classes, then yes, you can combine them in any order.

Can you select pseudo elements with JavaScript?

Since they're not part of the DOM, CSS pseudo-elements can't be selected and edited with JavaScript the same way as traditional elements on a page.

Can select have pseudo elements?

Syntax. You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement. Note: As a rule, double colons ( :: ) should be used instead of a single colon ( : ).


1 Answers

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
like image 131
radiaph Avatar answered Oct 01 '22 02:10

radiaph