Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Before-Content of CSS with jQuery

Tags:

jquery

css

I have the following CSS

h1:before {
    content: "Chapter " counter(lvl1) "\000d\000a";
    counter-increment: lvl1;
    white-space: pre-wrap;
}
h1 {
    page-break-before: right;
}

and this HTML

<p>...</p>
<h1>A Title</h1>
<p>...</p>

With the given CSS I get something like

Chapter 1
A Title

When I try to get the text with jQuery I get "A Title". Is there a possibility to get "Chapter 1\nA Title"?

Thanks

like image 563
MichaelS Avatar asked Feb 16 '13 17:02

MichaelS


1 Answers

Use getComputedStyle():

$('h1').each(function(){
    console.log(window.getComputedStyle(this,':before').content);
});

before() is a jQuery method used to traverse the DOM, it gets/sets the preceding element, it does not access the pseudo-element.

Working JS Fiddle, supplied by Eric.

Though there is the unfortunate caveat that this approach returns the literal string used in the content declaration, rather than the actual generated-content.

like image 173
David Thomas Avatar answered Oct 07 '22 21:10

David Thomas