简体   繁体   中英

check clicked element has class jQuery

This is my menu list. i need check if list item has specific class.

When I click the close button, I need to check if list item has active class.

My jQuery code is as below. but its not working.

 $("button").click(function(){ if($(this).hasClass('active')) { alert("active Yes"); } else{ alert("active"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="active"> <a href="#"> one</a> <button onclick="close()"> Close</button> </li> <li> <a href="#"> two</a> <button onclick="close()"> Close</button> </li> </ul>

How can I check if li has active class?

Select it with closest

$('button').on('click', function(){
  var btn = $(this);
  var li = btn.closest('li');
  var isActive = li.hasClass('active');
  console.log(isActive);
});

You should check for the parent element of the <button> which is the <li> element that has the class or not

 $("button").click(function(){ if($(this).parent().hasClass('active')) { alert("active Yes"); }else { alert("active"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="active"> <a href="#"> one</a> <button onclick="close()"> Close</button> </li> <li> <a href="#"> two</a> <button onclick="close()"> Close</button> </li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM