0

Why the onload event not triggered when elements are added in the following code:

function create() {
var para = document.createElement("p");     

para.setAttribute('onload', 'myFunction');

var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);


}

function myFunction() {
  alert(1);
}
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<br>

<button onclick="create()">create</button>

Is this not the proper way to set an attribute on an element or is the problem that the onload function is not fired?

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155

2 Answers2

1

Is this what you want?

function create() {
var para = document.createElement("p");

var node = document.createTextNode("This is new.");
para.appendChild(node);

para.onload = myFunction();

var element = document.getElementById("div1");
element.appendChild(para);


}

function myFunction() {
  alert(1);
}
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<br>

<button onclick="create()">create</button>
1

Try using DOMSubtreeModified event:

function create() {
var para = document.createElement("p");     

$("body").on('DOMSubtreeModified', para, myFunction());
//para.setAttribute('onload', 'myFunction');

var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);


}

function myFunction() {
  alert(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<br>

<button onclick="create()">create</button>
SpiderCode
  • 10,062
  • 2
  • 22
  • 42