Mara Barn Mara Barn - 26 days ago 9
CSS Question

How to detect class of the element

I would like to make that if I click on some of SOME TEXT item in .leftcol, it makes red the .rightcol item that has the same second category.

But I need that in one unique function, so the second class should be detected with the code.

I can't figure out how to complete the script:

<script>
$(document).ready(function(){
$('.leftcol DETECT SECOND CLASS').click(function() {
$('.rightcol DETECT SECOND CLASS').css('color', 'red');
});
});
</script>

<li class="leftcol aerospace-defense">SOME TEXT</li>
<li class="leftcol business-enablement">SOME TEXT</li>
<li class="leftcol cardiology">SOME TEXT</li>
<li class="leftcol cell-biology">SOME TEXT</li>


<li class="rightcol aerospace-defense" style="color: red;">Aerospace & Defense</li>
<li class="rightcol business-enablement" style="color: red;">Business Enablement</li>
<li class="rightcol cardiology" style="color: red;">Cardiology</li>
<li class="rightcol cell-biology" style="color: red;">Cell Biology</li>

Answer

The trick is here to catch the click events of any element with the leftcol class, and then read what the second class of that element is with the help of $(this).attr("class").split(' ')[1]:

$(document).ready(function(){
  $('.leftcol').click(function() {
    var secondClass = $(this).attr("class").split(' ')[1]
    $('.rightcol.' + secondClass).css('color', 'blue');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="leftcol aerospace-defense">SOME TEXT</li>
<li class="leftcol business-enablement">SOME TEXT</li>
<li class="leftcol cardiology">SOME TEXT</li>
<li class="leftcol cell-biology">SOME TEXT</li>
</ul>
<ul>
<li class="rightcol aerospace-defense" style="color: red;">Aerospace & Defense</li>
<li class="rightcol business-enablement" style="color: red;">Business Enablement</li>
<li class="rightcol cardiology" style="color: red;">Cardiology</li>
<li class="rightcol cell-biology" style="color: red;">Cell Biology</li>
</ul>

Comments