Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
Detect a word and addClass to body

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda