0

It is possible to detect if a class exists (Is there an "exists" function for jQuery?)

Is it possible to detect if a certain class exists between two other classes?

<div class="A"></div>

// if class B is not here - between anything with A follow directly by C, then put in B

<div class="C"></div>
Thomas
  • 33
  • 4

2 Answers2

0

You can use + selector in css. The below code will check if there is a C placed immediately after B and B placed immediately after A or not:

if ($('.A+.B+.C').length) {
  // Do something
} else {
  // Do something
}
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
0

You could check every .A element if its next neighbor not has class B. If so then add <div class="B"></div> in between.

jQuery

$(".A").each(function() {
    var a = $(this),
        n = a.next("div");
    
    if (n.length && n.hasClass("B") === false) {
        a.after('<div class="B">B</div>');
    }
});
.B { color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="A">A</div>
<div class="C">C</div>
<div class="A">A</div>

Vanilla JS

document.querySelectorAll(".A")
        .forEach(a => {
            const n = a.nextElementSibling || { tagName: "" };
        
            if (n.tagName === "DIV" && n.classList.contains("B") === false) {
                a.insertAdjacentHTML("afterEnd", '<div class="B">B</div>');
            }
        });
.B { color: red }
<div class="A">A</div>
<div class="C">C</div>
<div class="A">A</div>

Or if you know .A and .C then you could use the adjacent sibling combinator (+) to find all .C elements that are direct siblings of .A.

jQuery

$(".A + .C").before('<div class="B">B</div>');
.B { color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="A">A</div>
<div class="C">C</div>
<div class="A">A</div>

Vanilla JS

document.querySelectorAll(".A + .C")
        .forEach(c => {
          c.insertAdjacentHTML("beforeBegin", '<div class="B">B</div>');
        });
.B { color: red }
<div class="A">A</div>
<div class="C">C</div>
<div class="A">A</div>
Andreas
  • 21,535
  • 7
  • 47
  • 56