Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On click add class to child element without Jquery

I have a task where Jquery is not working, so I need a workaround to perform an add class event to child element of a div upon click event. How do I go about that. The Jquery for that purpose would be

$('.wpb_vc_column').click(function(e) {
  alert();
  e.preventDefault();
  $(this).find('.vc_controls').addClass('show-controls');
});
.show-controls {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wpb_vc_column">
  <div class="vc_controls">SomeThing</div>
</div>

Its basically a wordpress backend thing which need to be workable on mobile devices.

Regards

like image 388
Anup Gupta Avatar asked May 16 '18 06:05

Anup Gupta


1 Answers

You can use querySelectorAll() to select all the elements with class wpb_vc_column and associate the click event to each element. Then click on these element will find the child elements with class vc_controls and add the class to it.

function clickedColumn(e){
    e.preventDefault();
    if(this.querySelector('.vc_controls')){
      this.classList.add('show-controls');
    }
}
document.querySelectorAll('.wpb_vc_column').forEach(function(el){
  el.addEventListener('click', clickedColumn);
});
.show-controls{
  color:red;
}
<div class="wpb_vc_column">
  <div class="vc_controls">SomeThing 1</div>
  <div class="vc_controls">SomeThing 2</div>
</div>
like image 136
Ankit Agarwal Avatar answered Sep 17 '22 14:09

Ankit Agarwal