Problem changing target with javascript

2

I have a problem that I do not know how to solve. I attach the code snippet

<li id="menu-item-61" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-61">
  <a href="https://twitter.com/loquesea">
    <i class="icon-twitter"></i>
  </a>
</li>

The problem is that I need to add the target to a new tab on that link because I can not directly touch the html code.

I had created the following code:

function cambiatarget() {
  var links = document.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++) {
    links[i].target = "_blank";
  }
}
cambiatarget();

But the problem as it is logical is that I vary all the a of the page. How could I access that link only?

    
asked by Roberto 10.07.2017 в 16:49
source

1 answer

0

The problem is that in the statement document.getElementsByTagName("a") you are getting the reference all the elements a of your html. What you must do to solve the problem is to refer only to the element you need.

function cambiatarget() {
    var link = document.querySelector("#menu-item-61 a");
    link.target = "_blank";
}
cambiatarget();
<li id="menu-item-61" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-61">
    <a href="https://twitter.com/loquesea">
        <i class="icon-twitter">TWIIER</i>
    </a>
</li>
    
answered by 10.07.2017 / 16:59
source