I am struggling to dynamically create tags for each Subheading (h2 element) I have in my blog, and then fill those tags with the text of the Subheading.
This is what I have tried so far:
<script>
const subheadings = document.querySelectorAll("h2");
subheadings.forEach(function(x) {
document.getElementById("contents").innerHTML=x;
<a href='#' id="contents"></a>
});
</script>
This resulted in nothing appearing.
Any help or advice in which direction to look is greatly appreciated.
*** EDIT ***
I have updated the code to an answer that was given in the responses.
<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>
Hopefully, this gives all of the necessary information.
It however still doesn't display the text of the h2 elements but I think the logic is correct.