I am trying to create p tags and inside them span with insertAdjacentHTML method and give each one of them unique id, and after that I want to change or update the textContent, but I don't know the reason why it is not working?. If you have the solution please help me.
const wraper = document.querySelector("#wraper")
const place2 = "afterbegin";
const textOfTimerTile = `
<div >
<p id="program"><span id="programData"></span></p>
<p id="machineId"><span id="machineIdData"></span></p>
</div>
`;
wraper.insertAdjacentHTML(place2, textOfTimerTile);
const program = document.getElementById("program");
const programData = document.getElementById("programData");
const machineId = document.getElementById("machineId");
const machineIdData = document.getElementById("machineIdData");
program.textContent = "Program";
programData.textContent = "Program Span";
machineId.textContent= "Machine ID";
machineIdData.textContent= "Machine Span";
console.log("p tag ", program);
console.log("span ", programData)
#program, #machineId{
width: 150px;
height: 100px;
background-color: green
}
#programData, #machineIdData{
width:100px;
height: 60px;
background-color: red;
}
<div id="wraper"></div>
CodePudding user response:
According to MDN textContent:
Both textContent and innerText remove child nodes when altered. It is impossible to insert the nodes again into any other element or into the same element after doing so.
Meaning you override and inner elements of your <p>'s.
If you want, I suggest use innerHTML and add to it text instead of destroying your html structure with textContent.
However, since you set a new innerHTML you need to get the inner elements again.
To sum up -
const wraper = document.querySelector("#wraper")
const place2 = "afterbegin";
const textOfTimerTile = `
<div >
<p id="program"><span id="programData"></span></p>
<p id="machineId"><span id="machineIdData"></span></p>
</div>
`;
wraper.insertAdjacentHTML(place2, textOfTimerTile);
const program = document.getElementById("program");
const machineId = document.getElementById("machineId");
program.innerHTML = "Program" program.innerHTML;
const programData = document.getElementById("programData");
programData.innerHTML = "Program Span";
machineId.innerHTML = "Machine ID" machineId.innerHTML;
const machineIdData = document.getElementById("machineIdData");
machineIdData.innerHTML = "Machine Span";
#program,
#machineId {
width: 150px;
height: 100px;
background-color: green
}
#programData,
#machineIdData {
width: 500px;
height: 60px;
background-color: red;
}
<div id="wraper"></div>
CodePudding user response:
When you run program.textContent = "Program"; you're actually removing the span from the page (you can see that in the browser's dev tools).
What you can do instead is program.insertAdjacentText('afterbegin', 'Program')
