By Rakesh Sivaraman


2020-02-14 08:03:39 8 Comments

How can I get this output in CSS or jQuery.

::first-letter or CSS is (equal to) === "Some Value e.g. ' (1)(a)(I)(2)'" to get output background-color:red;

Sample HTML:

<p>(1)</p>
<p>(a)</p>
<p>(b)</p>
<p>(2)</p>
<p>(a)</p>
<p>(i)</p>
<p>(ii)</p>
<p>(iii)</p>

Output should be:

<p>(1)</p> <--Background-color RED
<p>(a)</p> <--Background-color GREEN
<p>(b)</p> <--Background-color GREEN
<p>(2)</p> <--Background-color RED
<p>(a)</p> <--Background-color GREEN
<p>(i)</p> <--Background-color YELLOw
<p>(ii)</p> <--Background-color YELLOw
<p>(iii)</p> <--Background-color YELLOw

2 comments

@Shree 2020-02-14 08:20:16

Use regex or substring to get first word from <p> tag. Add class based upon that text like below.

var $par = $("p");
$par.each(function(index, element) {
  var str = $(this).text().trim();
  var i = str.indexOf(" ");
  var txt = i == -1 ? str : str.substring(0, i);

  if (txt == '(1)' || txt == '(2)')
    $(this).addClass('red');
  if (txt == '(a)' || txt == '(b)')
    $(this).addClass('green');
  if (txt == '(ii)' || txt == '(iii)' || txt == '(i)')
    $(this).addClass('yellow')
});
.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  (1) 1st paragraph 
  (1) 1st paragraph
  (1) 1st paragraph
  next line
</p>
<p>(a) 2nd paragraph</p>
<p>(b)</p>
<p>(2)</p>
<p>(a)</p>
<p>(i)</p>
<p>(ii)</p>
<p>(iii)</p>

@Rakesh Sivaraman 2020-02-14 11:10:33

if the paragraph having newline this code is not working some error coming from REgex

@Shree 2020-02-14 11:36:30

See updated answer .

@Kavitha Velayutham 2020-02-14 08:19:46

You can try something like this

HTML

<div id="clr-change">
 <p>(1)</p>
 <p>(a)</p>
 <p>(2)</p>
 <p>(i)</p>
</div>

JQUERY

$( document ).ready(function() {
 $("#clr-change p").each(function(){
 if($( this ).html() == '(1)' || $( this ).html() == '(2)'){
 $( this ).css({'background-color':'#ff0000'});
    }else if('condition for green'){
    }
})
});

Related Questions

Sponsored Content

14 Answered Questions

[SOLVED] CSS 100% height with padding/margin

  • 2009-01-27 23:28:18
  • Toji
  • 325166 View
  • 802 Score
  • 14 Answer
  • Tags:   css

34 Answered Questions

45 Answered Questions

[SOLVED] How to disable text selection highlighting

26 Answered Questions

[SOLVED] Set select option 'selected', by value

36 Answered Questions

26 Answered Questions

[SOLVED] jQuery get value of selected radio button

13 Answered Questions

[SOLVED] How can I select an element with multiple classes in jQuery?

18 Answered Questions

[SOLVED] How can I remove a style added with .css() function?

40 Answered Questions

[SOLVED] How do I format a Microsoft JSON date?

16 Answered Questions

[SOLVED] Change the selected value of a drop-down list with jQuery

Sponsored Content