We help IT Professionals succeed at work.

Amend a link within a div using JS

Neil Thompson
on
Hi All

I want to be able to amend the link in this div but do not have access to the code, only the JS file, can someone advise the most basic JS code to amend this to simply "https://www.abc.co.uk/" please

 <div id="toplogo">
      <a title="Link to homepage" href="https://www.abc.co.uk/test/example">#</a>
</div>
Comment
Watch Question

Senior Systems Developer
Commented:

$("#toplogo a").attr("href", "https://www.abc.co.uk/");

Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
jQuery is not exactly the most basic code
You can do it like this
(document.querySelector('#toplogo a') || document.createElement('a')).href = "https://www.abc.co.uk/";

Open in new window

Works with plain JS - no jQuery required and fails over gracefully if #toplogo a does not exist
If #toplogo a is guaranteed to exist then you can simply do
document.querySelector('#toplogo a').href = "https://www.abc.co.uk/";

Open in new window