Federico
Federico

Reputation: 1422

If text inside <p> is X then addClass

I want to check what is the content in the nearest <p> and add a Class to a div accordingly.

Here's where I'm stuck.

$('p').each(function () {
    if ($('p').text() == 'E. A. K') {
        $('.pl1').addClass('service');
    }else{
        $('.pl2').addClass('service');
    }
});
.service:after{content:"(service)"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>

<span class=pl1>Player 1</span><br>
<span class=pl2>Player 2</span>

SO if the first <p> is E. A. K. then .pl1 has class service if the first <p> is F. F. then .pl2 has class service

Consider that there are many <p> all with those two contents. And some new will be added from time to time.

Upvotes: 0

Views: 136

Answers (2)

First you need to speed down things a bit, and make sure you close your brackets the correct places.

You say the <p> that appears closest to the top of the body, then you only want 1, so there is no need to loop through each <p>

This should do what you want, but still unsure since your logic is kinda strange, anyway hope it helps.

$('body p:first').filter(function() {
  if ($(this).text() == 'E. A. K.') {
    $('.pl1').addClass('service');
  } else {
    $('.pl2').addClass('service');
  }
});

Demo

$('body p:first').filter(function() {
  if ($(this).text() == 'E. A. K.') {
    $('.pl1').addClass('service');
  } else {
    $('.pl2').addClass('service');
  }
});
.service:after {
  content: "(service)"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>

<span class=pl1>Player 1</span><br>
<span class=pl2>Player 2</span>

Upvotes: 2

Sneha Shinde
Sneha Shinde

Reputation: 58

$('p:first').map(function() {
  if ($(this).text() == "E. A. K.") {
    $('.pl1').addClass('service');
  } else {
    $('.pl2').addClass('service');
  }
});
.service {
  color: red;
}

.service:after {
  content: "(service)"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>E. A. K.</p>
<p>F. F.</p>

<span class="pl1">Player 1</span><br>
<span class="pl2">Player 2</span>

Upvotes: 0

Related Questions