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?

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

Answers 1

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

    Live jsFiddle

        var page = "<?= json_encode($page); ?>";

Related Articles