Reputation: 255
I have a pseudoelement :after content defined in CSS.
div:after {
content:'This is the sentence.';
}
Can anyone please advise me how to target the first character of the content and change its style. Jquery is OK but I'm trying to do it with first* pseudoelement.
Upvotes: 1
Views: 783
Reputation: 268414
You won't be able to do anything like div::after::first-letter
for the time being, but you can achieve the same end-results relatively easily by merely creating the content you wish to manipulate, and injecting it into your DOM where the div::after
pseudo elements would have been placed had they been used:
(function () {
var aftr = document.createElement( "div" ),
divs = document.querySelectorAll( "div" );
aftr.className = "after";
aftr.textContent = "This is the sentence.";
for ( var i = 0; i < divs.length; i++ ) {
divs.item(i).appendChild( aftr.cloneNode( true ) );
}
}());
With these elements now in place, you can move on to styling them:
.after:last-child::first-letter {
color: red;
padding: .5em 1em;
border: 1px solid red;
}
Fiddle: http://jsfiddle.net/jonathansampson/7gmbvewh/
One thing that immediately makes me uncomfortable is the distance between the markup and the text you want displayed within these elements. You could place the text within the markup as a data attribute:
<div data-after="After content">Original Content</div>
And then use that (if it exists) in the final loop:
for ( var i = 0; i < divs.length; i++ ) {
var clone = aftr.cloneNode( true ),
after = divs.item(i).dataset.after;
if ( after ) {
clone.textContent = after;
}
divs.item(i).appendChild( clone );
}
Fiddle: http://jsfiddle.net/jonathansampson/7gmbvewh/2/
Upvotes: 1
Reputation: 723974
The only time :first-letter
could possibly match the first letter of an :after
pseudo-element is if the pseudo-element is inline, and there is no other content preceding the pseudo-element (at least in the usual LTR writing mode anyway). Furthermore, pseudo-elements cannot contain their own pseudo-elements, so you couldn't do :after:first-letter
either.
If your div
element has content, then you won't be able to do this using an :after
pseudo-element. You will need to use an actual child element instead. You can easily generate one using jQuery's .append()
method, but if you want to target :first-letter
of that element, you will need to display it as either block or inline-block instead of inline:
$('div').append('<span class="after">This is the sentence.</span>');
div > .after {
display: inline-block;
}
div > .after:first-letter {
color: red;
}
Upvotes: 1
Reputation: 31961
If this is a feature question, then the answer is:
Unfortunatelly you can't target and manipulate with pseudo-elements.
But there are workarounds (don't use :after
, but actual elements), read the comments under your question.
Upvotes: 0