Set dynamic selector in jQuery

I want to pass dynamic selector in jQuery, Consider following example here I have one variable $page and I want to pass that as a selector to add class. $page contains page name such as Dashboard, Maps, Profile etc, Following code shows that how manually I added the selector, again one thing is that I don't want to use if-else conditions. Is it possible with any way?

<script>
  $(document).ready(function(){
    var page = <?php echo json_encode($page);?>;
    $("#Dashboard").addClass('active');        //HERE TO PASS DYNAMIC SELECTOR
  });
</script>

Answers 1

  • If we consider this <?= json_encode($page); ?> returns 'Dashboard' or 'Maps' ...
    You can simply do it like this:

    Live jsFiddle

    $(document).ready(function(){
        var page = "<?= json_encode($page); ?>";
        $("#"+page).addClass('active');
    });
    

Related Articles