2

I have two divs with the same class name as :

<button>Click to change font weight.</button>

<div class="wt">Paragraph 1</p>
<div class="wt">Paragraph 2</p>

Using jQuery, I'm trying to change the font-weight of the div that has "Paragraph 1" as text. What would be the best way to approach this? This is what I'm trying - but it would of course set both the divs' text to bold:

  $("button").click(function(){
    if($(".wt").text().trim() == "Paragraph 1")
    {
        $(".wt").css("font-weight","bold" )  
    }
  });
});
Sarvesh Mahajan
  • 914
  • 7
  • 16
221b
  • 431
  • 1
  • 11
  • 34

4 Answers4

2

You can use jQuery contains() method:

$(".wt:contains(Paragraph 1)").css("font-weight","bold" )
Ankur Mishra
  • 1,284
  • 1
  • 6
  • 15
1

For your query, I would add class instead:

$('.wt:first').addClass('font-weight-bold');

If you're using bootstrap 4, it would automatically support the class. Otherwise, add this rule in your stylesheet:

.font-weight-bold {
  font-weight: bold;
}

If your paragraph is not the first in the DOM Tree and looking for the text, then use contains selector as suggest in other answer:

$('.wt:contains("Paragraph 1")').addClass('font-weight-bold');

One last thing, I forgot about to mention that you can use toggleClass to toggle the changes upon button clicks.

$('.wt:first').toggleClass('font-weight-bold');
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

You can use jQuery's :contains() selector.

I've added some additional functionality so you can toggle between font-weight's. It is worth noting that calling .css('font-weight') with jQuery will not return you string values such as normal or bold; instead calling this will retrieve numbers ('400' === 'normal', '700' === 'bold' etc).

$("button").click(function() {
  let par1 = $(".wt:contains('Paragraph 1')");

  // Toggle between font-weights
  par1.css(
    'font-weight',
    (['normal', '400'].indexOf(par1.css('font-weight')) === -1) ? 'normal' : 'bold'
  );

  // Or, uncomment and use this if you do not wish to toggle the div
  // par1.css('font-weight', 'bold');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Click to change font weight.</button>

<div class="wt">Paragraph 1</div>
<div class="wt">Paragraph 2</div>

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
0
 $("button").click(function(){
   $(".wt").each(function(){
     if($(this).text() == "Paragraph 1")
     $(this).css("font-weight","bold");
   });
 });
harsh_apache
  • 433
  • 4
  • 10
  • 1
    Please edit your answer with a textual explanation of the code snippet and explain how it answers the question – chevybow Feb 26 '20 at 22:53