Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
how to select any href using JavaScript?

The following code is used for my sidebar to be able to set the active subpage and properly display the the sidebar when refreshing the page.

It works well if I add the "#" symbol to the href of the subpages but didn't work when changing the href to anything else and removing the "#" symbol. Let's suppose I want to set the href as "/contactpage/. How do I indicate in the below code to choose any href not only the ones that contains the hash symbol?

  <script>

      (() => {
        'use strict'
      
      
      
        function setActiveItem() {
          const { hash } = window.location
      
          if (hash === '') {
            return
          }
      
          const link = document.querySelector(`.d-flex a[href="${hash}"]`)
      
          if (!link) {
            return
          }
      
          const active = document.querySelector('.d-flex .active')
          const parent = link.parentNode.parentNode.previousElementSibling
      
          link.classList.add('active')
      
          if (parent.classList.contains('collapsed')) {
            parent.click()
          }
      
          if (!active) {
            return
          }
      
          const expanded = active.parentNode.parentNode.previousElementSibling
      
          active.classList.remove('active')
      
          if (expanded && parent !== expanded) {
            expanded.click()
          }
        }
      
        setActiveItem()
        window.addEventListener('hashchange', setActiveItem)
      })()
      
      
      
      </script> 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

// Select anything with an "href" attribute, regardless of its value
document.querySelectorAll('[href]')

// Select only the first link with the current page's path ("active" link)
const currentPath = window.location.pathname
document.querySelector(`a[href="${currentPath}"]`)

// Select the currently active path including the hash
const currentPathWithHash = window.location.pathname + window.location.hash
document.querySelector(`a[href="${currentPathWithHash}"]`)

To avoid issues when none of the links contain hashes, just remove the first few lines of your code up to const link = ..., which should be replaced by one of the options above (edit to suit your needs).

I also noticed that if active is also the current link, you'll end up first adding the active class to it and deleting it later in your code. Switch the order like this to avoid that:

active.classList.remove('active')
link.classList.add('active')

Note that if there could be more than one link on the page that point to the current path, you should probably add further selectors, like a class name you use for the target links. Unless of course you want to target any link with that path, in which case just use document.querySelectorAll. Yours seem to be under a .d-flex container, so add that to my examples.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda