I've been grappling with the challenge of dynamically generating <a>
tags for each Subheading (h2 element) on my blog and then populating those tags with the text from the Subheadings.
Here's what I've attempted so far:
<script>
const subheadings = document.querySelectorAll("h2");
subheadings.forEach(function(x) {
document.getElementById("contents").innerHTML=x;
<a href='#' id="contents"></a>
});
</script>
Unfortunately, this didn't yield any visible results.
Any guidance or recommendations on where to focus my efforts would be greatly welcomed.
*** EDIT ***
I have incorporated the code snippet provided in one of the responses. Here's the updated version:
<div class="col-3" id="contents-table">
<script>
const subheading = document.querySelectorAll('h2');
subheading.forEach(function(x) {
let xbe = x.innerText.split(' ');
for (let i = 0; i<xbe.length;i++) {
const div = document.getElementById('contents-table');
let a = document.createElement('a');
a.innerText = xbe[i];
console.log( a.innerText);
div.append(a);
}
});
</script>
</div>
I trust that this update contains all the pertinent details.
However, although it follows what seems to be the correct logic, it still doesn't render the text of the h2 elements as intended.