Reputation: 5
I need to append a separate div with the title "Lucky!" as a child of another div element. I have written the exact code inside the createTextNode event but it is not computing the exact code.
I have tried using different event handlers or writing the JavaScript in different places but nothing will show at all then.
function function2() {
var childtype = document.createElement("div");
var childcontent = document.createTextNode("<div title='Lucky!'>See you!</div>");
childtype.appendChild(childcontent);
document.getElementById("div1").appendChild(childtype);
}
function2()
It writes <div title='Lucky!'>See you!</div>
instead of just See you!
with the properties.
Upvotes: 0
Views: 59
Reputation: 8589
You have to create both nodes separately and set the text of the inner node. You can then add the title using setAttribute()
on the node you created.
function function2() {
var outer = document.createElement("div");
var inner = document.createElement("div");
var childcontent = document.createTextNode("See you!");
inner.appendChild(childcontent);
inner.setAttribute( 'title', 'Lucky!' );
outer.appendChild(inner);
document.body.appendChild(outer);
}
function2();
As mentioned, the alternative is using innerHTML, since that will parse the HTML:
function function2() {
var childtype = document.createElement("div");
childtype.innerHTML = "<div title='Lucky!'>See you!</div>";
document.getElementById("div1").appendChild(childtype);
}
function2();
<div id="div1"></div>
Upvotes: 2