Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and pseudo-elements

I tried to dynamically change the position of an element which is defined in CSS with :after. Using this:

$(function(){
    $('div::after').css({'top':'20px'})
})

But it doesn't work. Are there any ways to change the position?

like image 801
rsboarder Avatar asked Jan 23 '12 08:01

rsboarder


People also ask

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.

What are pseudo elements?

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.

What are jQuery elements?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)


2 Answers

You can't. Content created by :after or :before is not part of the DOM and therefore cannot be selected or modified.

If you have a look at this example fiddle and inspect the DOM in Firebug or similar you will see that the pseudo-element is not present in the DOM tree.

A potential solution would be to apply a class to the element you want to change, and to style that class appropriately in CSS:

$("div").addClass("newClass");

See this fiddle for an example.

like image 52
James Allardice Avatar answered Oct 09 '22 07:10

James Allardice


add CSS:

p.special:before {
    content: "bar";
    position: absolute;
    top : 10px;
}

assuming the style sheet where the code above was put is the first one on the page, use this to change it:

document.styleSheets[0].addRule('p.special:before','top: 15px;');
like image 31
ordman Avatar answered Oct 09 '22 08:10

ordman