Good day. I was given the task to make the active menu field stand out. I did it without any problems using jQuery, but I was told that because of the principles, I need to do this on javascript'e. And then I had a problem. JQuery code:

$(document).ready(function() { var url=document.location.href; $.each($(".mainMenu a"),function(){ if(this.href==url){$(this).addClass('activeClass'); $("span",this).removeClass('bracket').addClass('activeClassBrackets'); }; }); }) 

HTML:

 <ul class="mainMenu"> <li><a href="/"><span class="bracket">[</span>Main<span class="bracket">]</span></a></li> <li><a href="/1"><span class="bracket">[</span>1Page<span class="bracket">]</span></a></li> <li><a href="2"><span class="bracket">[</span>2Page<span class="bracket">]</span></a></li> <li><a href="3"><span class="bracket">[</span>3Page<span class="bracket">]</span></a></li> </ul> 

    1 answer 1

     document.querySelector('.mainMenu a[href="'+window.location.href+'"]').classList.add('activeClass'); document.querySelector('.mainMenu .activeClass span.bracket').classList.remove('bracket'); 
    • Unfortunately, it gives this error, Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '.mainMenu a [href = localhost: 3000/3] ' is not a valid selector . Is it possible to fix it somehow? - ItsMyLife
    • @ItsMyLife someone gives you tasks, and you do them using the library without knowing the basics of pure js? How is this possible? Learn and understand, the problem is elementary. And all that will be used in it is querySelectorAll('.mainMenu a') , a loop on elements and el.classList.add('') el.classList.remove('') - Vasily Barbashev
    • @ItsMyLife, corrected, you must take the url in quotes. And there is no need for cycles for this task at all, but it is necessary to check the existence of the element - Artem Gorlachev
    • forgot activeClassBrackets , besides with the wrong solution brackets - there are two of them, and you only change one - Grundy
    • @Grundy, yes, exactly, but I would delete the classes on the span altogether, everything can be done by the parent class - Artem Gorlachev