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

4 answers

  • answered 2018-05-16 06:21 vijesh

    var myEle = document.getElementsByClassName('vc_controls');
    myEle.className = "show-controls";
    

  • answered 2018-05-16 06:21 Pranay Rana

    make use of querySelector method and and search for child in parent element

    el.querySelector("#child").className = 'show-controls';
    or  
    el.querySelector('.vc_controls').className = 'show-controls';
    

  • answered 2018-05-16 06:35 Libin C Jacob

    function changeClass(element){
    var get_vc_controls=element.getElementsByClassName('vc_controls');
    get_vc_controls[0].className='show-controls';
    }
    .show-controls {
      color: red
    }
    <div class="wpb_vc_column" style="border:1px solid;" onclick="changeClass(this)">
      <div class="vc_controls">SomeThing</div>
    </div>

  • answered 2018-05-16 06:43 Ankit Agarwal

    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>