Give body class if certain combination of elements exists in the DOM

264
April 26, 2017, at 3:18 PM

I want to give the body a class when a specific combination of classes exists.

Lets say the markup looks like this:

<span class="target one"></div>
<span class="target two"></div>
<span class="target three"></div>
<span class="target four"></div>
<span class="target five"></div>

The target class will be the one thats needs to be targeted. If any combination involving only any of the three first classes - one two or three is present - give body a class.

Exampel (just showing three combination of the target elements to visualize):

<span class="target one"></div>
<span class="target one"></div>
<span class="target one"></div>
<span class="target two"></div>
<span class="target three"></div>
<span class="target two"></div>

etcetera.

But no class if any of the other elements are present. These are dynamic so i cant use them as variables.

<span class="target one"></div>
<span class="target one"></div>
<span class="target four"></div>

Is this possible?

Answer 1

This might be what you are looking for.

var d = ["one", "two", "three"]; 
var t = []; 
$('span.target').each(function(i) { 
  t.push($(this).attr("class").replace("target ", "")); 
  if (i == ($('span.target').length - 1)) { 
    var l = true; 
    for (i = 0; i < t.length; i++) { 
      if ($.inArray(t[i], d) == -1) 
      { 
        l = false; 
      } 
    } 
    if(l){ 
      $("body").addClass("AddMyClass") 
    } 
  } 
}) 
 
console.log("The body has the class AddMyClass: " +$("body").hasClass("AddMyClass"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<span class="target one"></div> 
<span class="target two"></div> 
<span class="target three"></div>

Rent Charter Buses Company
READ ALSO
Wordpress AJAX File Upload

Wordpress AJAX File Upload

I am having trouble saving the uploaded file to the Wordpress database:

416
How to skip a value when using next and previous for swal messages?

How to skip a value when using next and previous for swal messages?

The next and previous work to show swal messagesI want to be able to skip a certain variable/

240
Which is better - nLog or Elmag for logging Js errors/info?

Which is better - nLog or Elmag for logging Js errors/info?

I want to log the response from api calls in order to trace what error messages or error codes are there as it is not always that the api call gives you a 400 error only

268
How can I catch a jQuery change event when I am manually changing the input value through another jQuery?

How can I catch a jQuery change event when I am manually changing the input value through another jQuery?

Well I am facing a problem to handle the change event of a input fieldBecause I am changing the text of the input field by another script

310