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 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.
CodePudding user response:
html:
<h2>
test example two!
test example two!
test example two!
</h2>
<div ></div>
css:
.holder {
width:1200px;
height:20px;
display: flex;
}
js:
const subheading = document.querySelectorAll('h2');
const cont = document.querySelector('.container')
subheading.forEach(function(x) {
cont.innerHTML = ''
let xbe = x.innerText.split(' ');
for (let i = 0; i<xbe.length;i ) {
const test = document.createElement('div');
test.classList.add('holder')
let a = document.createElement('a');
a.href=''
a.innerText = xbe[i];
console.log(a);
test.append(a);
cont.append(test)
}
});