Home > front end >  Detect a word and addClass to body
Detect a word and addClass to body

Time:09-27

The jQuery below detects the word first and third in any <p> text and adds a yellow or red background to it.

$(document).ready(function(){
  $("p:contains(first)").css("background-color", "yellow");
  $("p:contains(third)").css("background-color", "red");
});

<p>I'm the first sentence.</p>
<p>I'm the second sentence.</p>
<p>I'm the third sentence.</p>
<p>I'm the fourth sentence.</p>

JSFiddle: https://jsfiddle.net/3p0nmw4f/1/

However, instead of highlighting the text, I want to addClass to the body of the html document like this :

<body class="first">

or

<body class="third">

I know we can achieve this using $(document.body).addClass('first'); but I'm unable to put it together.

Please help.

CodePudding user response:

You could search for the closest body HTML element. You can do this by doing the following:

$(document).ready(function(){
  $("p:contains(first)").closest('body').addClass('first');
  $("p:contains(third)").closest('body').addClass('third');
});

Another possibility would be to simply search for the body element as follows:

$(document).ready(function(){
  if ($("p:contains(first)"))
    $("body").addClass("first")
  if ($("p:contains(third)"))
    $("body").addClass("third")
});

Source: https://jsfiddle.net/fk05dabw/

  • Related