I am looking for a solution to my problem. The situation is as follows. I have the following div's
<div class="group">
<div class="A1_B1 symptom">Bla Bla Bla</div>
<div class="class1 symptom">Bla Bla Bla</div>
<div class="A1_B1 symptom">Foo Foo Foo</div>
<div class="A1_B3 symptom">Con Con Con</div>
<div class="A1_B1 symptom"><a href="#" class="connect">Click Me</a></div>
</div>
When I click the DIV class="A1_B1", I have to instert some html after class="A1_B1" with the following conditions: (i) The html should not be inserted after the clicked DIV. (ii) The html should not be inserted after any DIV that has the immediate next class="class1".
Based on the given conditions, the html should appear like this -
<div class="group">
<div class="A1_B1 symptom">Bla Bla Bla</div>
<div class="class1 symptom">Bla Bla Bla</div>
<div class="A1_B1 symptom">Foo Foo Foo</div>
<div class='class2'>Bar Bar Bar</div>
<div class="A1_B3 symptom">Con Con Con</div>
<div class="A1_B1 symptom"><a href="#" class="connect">Click Me</a></div>
</div>
...and here is what I have written, which does not work. Can anyone help me with this problem. Thanks in advance.
$(document).on("click", ".connect", function (ev) {
var thisClass = $(this).parents('div.symptom').attr('class');
var html = "<div class='class2'>Bar Bar Bar</div>";
$(html).insertAfter("A1_B1":not("."+thisClass).next('div:not(.class1)'));
});
You can use .each
loop to iterate through your symptom
divs .Then, inside this check if next div doesn't have class class1
depending on this add your html after that div .
Demo Code :
$(document).on("click", ".connect", function(ev) {
var selector = $(this).closest(".group")
var not_to_compare = $(this).parent();
//loop through all divs ..
selector.find(".A1_B1").not(not_to_compare).each(function() {
//if neext class is not class1
if (!$(this).next().hasClass("class1")) {
var html = "<div class='class2'>Bar Bar Bar</div>";
$(html).insertAfter($(this)) //add there
}
})
});
.class2 {
color: red
}
.class1 {
color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="group">
<div class="A1_B1 symptom">Bla Bla Bla</div>
<div class="class1 symptom">Bla Bla Bla</div>
<div class="A1_B1 symptom">Foo Foo Foo</div>
<div class="A1_B3 symptom">Con Con Con</div>
<div class="A1_B1 symptom"><a href="#" class="connect">Click Me</a></div>
</div>