Reputation: 904
A sample text inside a div:
I am at the first line.
I am at the second line.
I am at the third line.
I am at the end of the first paragraph.
Problem: I want to make a script that will make:
- All "first" will be colored blue
- All "second" will be colored green
- All "third" will be colored red and BOLD
Please see the non working code here..
Added a link for the code
Upvotes: 0
Views: 122
Reputation: 36
Here you go
$(function(){
$('#text').attr('value','first').css('color','#0000FF');
$('#text').attr('value','second').css('color','#00FF00');
$('#text').attr('value','third').css('color','#FF0000');
$('#text').attr('value','third').css('font-weight','bold');
});
Upvotes: 2
Reputation: 578
You can do this using jQuery :nth-child
selectors. You can apply styles using css() or by adding classes to the paragraphs and styling them with CSS (which would be ideal).
I've created a JSFiddle with the two versions: http://jsfiddle.net/RJ8sC/5/. You just need to change the wrapper div ID to yours and you should be good to go.
Here's the jQuery code for quick reference:
$(document).ready( function() {
$('#example p:nth-child(1)').css('color','blue');
$('#example p:nth-child(2)').css('color','green');
$('#example p:nth-child(3)').css({color:'red', 'font-weight': 'bold'});
});
// ALTERNATIVE USING CLASSES - THIS IS BETTER PRACTICE
$(document).ready( function() {
$('#example2 p:nth-child(1)').addClass('first');
$('#example2 p:nth-child(2)').addClass('second');
$('#example2 p:nth-child(3)').addClass('third');
});
Upvotes: 0
Reputation: 2557
this will be almost impossible to achieve and if worked for one article or paragraph it wont work for the other .. in my point of view the only solution will be including an html markup that will define those and then apply the jquery code for them ,
<p class='paragraph'>
<span class='firstline'>This is the first line.</span>
<span class='secoundline'> This is the second line. </span>
<span class='thirdline'> This is the third line.</span>
<span class='endparagraph'>This is the end of the first paragraph.</span>
</p>
now in the jquery part you can do something like
$(function(){
$('.firstline').css({'color':'blue' , 'font-weight':'bold'});
.....
})
Upvotes: 0