I am creating a paragraph dynamically adding it and then assigning an id to it. While the paragraph gets created, the id does not. I have kept an alert which returns undefined. This is possibly because the code for creating the id gets executed before the paragraph. is created. Is there a way to wait for the element to be created and then assign the id. Some. event listener, or action completions listener. Here is the code that I have taken and modified to explain what I am trying to do:
function myFunction() {
var h = document.getElementById("myH2");
var test = "<p>My new paragraph</p>";
h.insertAdjacentHTML("afterend", test);
test.id = "1234";
alert(test.id);
}
<!DOCTYPE html>
<html>
<body>
<p>Insert a specified text as HTML, in the document.</p>
<h2 id="myH2">My Header</h2>
<p>Click the button to insert a paragraph after the header:</p>
<button onclick="myFunction()">Insert a paragraph</button>
</body>
</html>