Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 337
Abhijit Kumbhar Avatar asked Dec 05 '25 05:12

Abhijit Kumbhar


1 Answers

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');
});
like image 98
Siamak Motlagh Avatar answered Dec 06 '25 19:12

Siamak Motlagh