Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have this styling:

section.tipos .content > div:before {
    background: none repeat scroll 0 0 #DDDDDD;
    content: " ";
    height: 10px;
    left: 32%;
    position: absolute;
    top: -10px;
    width: 10px;
}

Which works fine,

But when some events happen I would like to change the left property for a different %

I know this could be achieved (for sure) using classnames or styles. But my boss doesn't like much the class names unless they're 100% needed.

Question is: Can I alter the css for a pseudo selector from javascript? Something like this (but that works)

$('section.tipos .content > div:before').css({ 'left' : 50+index*17});
share|improve this question
 
unfortunately you need a workaround for this, like appending a new <style> for the element and set !important –  Spokey Jun 14 '13 at 12:35
add comment

marked as duplicate by user3237539, Josh Mein, jball, Jaguar, Samuel Caillerie Jun 14 '13 at 17:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

No you can't do that. The :before and :after pseudo-elements are not available in any way to your Javascript code.

The best work-around you can hope for is to use your Javascript to change the class of the main element, and have separate CSS code for the :before pseudo-element depending on which class it has.

Then you could have CSS code like this:

section.tipos .content > div.newClass:before {
    ....
}

However, I note that you're wanting to set the width to a calculated value; that might be tricky using the above technique. CSS calc() may help, depending what index is being used for, and depending what level of browser support you need.

share|improve this answer
add comment

Try appending '%' to the css style value:

$('section.tipos .content > div:before').css({ 'left' : 50+index*17 + '%'});
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.