0

I would like to change the href of the in this code:

<div class ="amp-logo">
    <a href="http://www.google.com" title="Google"></a>
</div>

I tried to use this code:

<script>
let link = document.querySelector('.amp-logo').getElementsByTagName('a');
link.href = window.origin+'/blog';
<\script>

but my code is not working. Someone can help me?

1 Answers1

2

The problem with your code is that getElementsByTagName returns an array of objects. You could make it work like so:

let link = document.querySelector('.amp-logo').getElementsByTagName('a');
link[0].href = window.origin+'/blog'; // see the [0] here
<div class="amp-logo">
    <a href="http://www.google.com" title="Google">X</a>
</div>

But you can select the <a> element directly like so

let link = document.querySelector('.amp-logo > a');
link.href = window.origin+'/blog';
<div class="amp-logo">
    <a href="http://www.google.com" title="Google">X</a>
</div>

or you could also only use the title attribute selector like so

let link = document.querySelector('[title="Google"]');
link.href = window.origin+'/blog';
<div class="amp-logo">
    <a href="http://www.google.com" title="Google">X</a>
</div>

or a combination of both methods like

let link = document.querySelector('.amp-logo [title="Google"]');
caramba
  • 21,963
  • 19
  • 86
  • 127