Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the href inside of a div using javascript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"]');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading