Skip to content
Advertisement

How to add/update text of elements created with insertAdjacentHTML method?

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 class="dataWraper">
<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>

Advertisement

Answer

Now, I don’t know that complete context for your code, but an alternative could be to make use of the template literal (template string) that you already defined.

const wraper = document.querySelector("#wraper");

let programtext = "Program";
let programDatatext = "Program Span";
let machineIdtext = "Machine ID";
let machineIdDatatext = "Machine Span";

const textOfTimerTile = `<div class="dataWraper">
<p id="program">${programtext}<span id="programData">${programDatatext}</span></p>
<p id="machineId">${machineIdtext}<span id="machineIdData">${machineIdDatatext}</span></p>
</div>`;

wraper.innerHTML = textOfTimerTile;
#program,
#machineId {
  width: 150px;
  height: 100px;
  background-color: green
}

#programData,
#machineIdData {
  width: 100px;
  height: 60px;
  background-color: red;
}
<div id="wraper"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement