Find ID name of sibling element and add to href

I’m creating a long document with a lot of sub-sections and would like to automate some steps with some JS. (It’s a static page in a rudimentary CMS.)

I have lots of this:

<div class="title">
  <h3 id="oranges">Oranges are great</h3>
  <a href="XXXX" class="url">Link to this section</a>
</div>

<div class="title">
  <h3 id="apples">Apples are great</h3>
  <a href="XXXX" class="url">Link to this section</a>
</div>

What I’d like to do is grab the ID name of the H3 and automatically insert it as an anchor in the href=”” of the link. Is this possible?

So the link (.url) has “#organges” or “#apples” as a href, if that makes sense.

jQuery is already loaded, if that makes it easier.

Answer

My suggestion (Vanilla JS):

var divs = document.querySelectorAll('.title');

for (var div of divs) {
  var el = div.children;
  el[1].href = '#' + el[0].id;
};
<div class="title">
  <h3 id="oranges">Oranges are great</h3>
  <a href="XXXX">Link to this section</a>
</div>
<div class="title">
  <h3 id="apples">Apples are great</h3>
  <a href="XXXX">Link to this section</a>
</div>
<div class="title">
  <h3 id="cherries">Cherries are great</h3>
  <a href="XXXX">Link to this section</a>
</div>

EDIT #1 (2021-08-29)

Assuming that, in your HTML code, <a> (whatever its “class” may be) comes always right after <h3>, you can alternatively do this:

var els = document.querySelectorAll('.title h3');

for (var el of els) el.nextElementSibling.href = '#' + el.id;
<div class="title">
  <h3 id="oranges">Oranges are great</h3>
  <a href="XXXX">Link to this section</a>
</div>
<div class="title">
  <h3 id="apples">Apples are great</h3>
  <a href="XXXX">Link to this section</a>
</div>
<div class="title">
  <h3 id="cherries">Cherries are great</h3>
  <a href="XXXX">Link to this section</a>
</div>

EDIT #2 (2021-08-30)

Following your last comment:

var els = document.querySelectorAll('.title');

for (var el of els) el.querySelector('.url').href = '#' + el.querySelector('h3').id;
<div class="title">
  <h3 id="oranges">Oranges are great</h3>
  <a href="XXXX" class="url">Link to this section</a>
</div>
<div class="title">
  <h3 id="apples">Apples are great</h3>
  <a href="XXXX" class="url">Link to this section</a>
</div>
<div class="title">
  <h3 id="cherries">Cherries are great</h3>
  <a href="XXXX" class="url">Link to this section</a>
</div>