'Can I merge two $("# myDiv") into one line? [duplicate]
I added a function to the menu that adds an active class to various items when they are on the current page. Works well.
My question is if I can shorten the code somehow to have a clean file. So I wanted to try to reduce the two $ variables into one line, but I don't know if that's possible.
Sorry, but I'm new. The ultimate goal is to shorten the code as much as possible. Maybe if there are other ways to do this I would be curious to try them. I appreciate every answer, thanks.
This is Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if(window.location.href.indexOf("/settings/") > -1) {
$("#menu-item-1").addClass('current_menu');
$("#menu-link-1").addClass('current_link');
}
});
</script>
<nav>
<ul class="nav">
<li id="menu-item-1"><a id="menu-link-1" href="https://mywebsite.com/account/settings">Settings</a></li>
</ul>
</nav>
this is what i try to do to shorten but it doesn't work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if(window.location.href.indexOf("/settings/") > -1) {
$("#menu-item-1", "#menu-link-1").addClass('current_menu current_link');
}
});
</script>
<nav>
<ul class="nav">
<li id="menu-item-1"><a id="menu-link-1" href="https://mywebsite.com/account/settings">Settings</a></li>
</ul>
</nav>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
