How to manipulate part of the href attribute of a link using JavaScript in WordPress?

2

Is it possible to manipulate only part of the URL using DOM or something like this?

I would like to remove the '#' in the middle of the url, in the href attribute.

The code will be added in a Wordpress theme and should be enabled when loading the page.

How are you currently:

<div class="rodape">
   <a class="azul" href="http://site.com/departamento/#consultoria-um"
   title="Detalhes">Detalhes</a>
   <a class="azul" href="http://site.com/departamento/#consultoria-dois"
   title="Detalhes">Detalhes</a>
</div>

End result (no link #):

<div class="rodape">
   <a class="azul" href="http://site.com/departamento/consultoria-um"
   title="Detalhes">Detalhes</a>
   <a class="azul" href="http://site.com/departamento/consultoria-dois"
   title="Detalhes">Detalhes</a>
</div>
    
asked by anonymous 31.01.2017 / 02:37

3 answers

0

A different way:

document.querySelectorAll('.rodape a').forEach(function(el) {
  el.setAttribute('href', el.getAttribute('href').replace('#', ''));
  console.log(el);
});
<div class="rodape">
   <a class="azul" href="http://site.com/departamento/#consultoria-um"
   title="Detalhes">Detalhes</a>
   <a class="azul" href="http://site.com/departamento/#consultoria-dois"
   title="Detalhes">Detalhes</a>
</div>

I use the .rodape a selector to get all the anchor inside the div with the rodape class, and I loop the elements, then shoot # with the function replace and update the href attribute with the link formatted.

    
31.01.2017 / 12:05
1

Yes, you can do this by capturing the value of the href attribute and manipulating it.

Functional example

document.getElementById('bt-remover-hashs').addEventListener('click', removerHashtags);

function removerHashtags(){
  var links = document.getElementById('rodape').getElementsByTagName('a');

  for(var i = 0; i < links.length; i++){  
    links[i].href = links[i].href.replace('#', '');  
    console.log(links[i].href);
  }
}
<div class="rodape" id="rodape">
   <a class="azul" href="http://site.com/departamento/#consultoria-um"
   title="Detalhes">Detalhes</a>
   <a class="azul" href="http://site.com/departamento/#consultoria-dois"
   title="Detalhes">Detalhes</a>
</div>

<button id="bt-remover-hashs">Remover #</button>
    
31.01.2017 / 02:45
1

If you use jquery it follows the code:

newlink = $(".azul").attr("href").replace("#","");
$(".azul").attr("href",newlink);
    
31.01.2017 / 03:37