问题
I'm pretty sure I already know the answer to this but I kind of would like an explanation.
I want to create and append an element without having to define it in a variable (it seems like such a waste to me and is unnecessary).
var errorMessage = document.getElementById("errorMessage");
errorMessage.innerHTML = "";
errorMessage.appendChild(document.createElement('p').appendChild(document.createTextNode("Due to an egg allergy, your child will NOT receive the flu vaccine.")));
So this actually appends the text node into the errorMessage element, but will not generate the 'p' tag.
I just think its ridiculous that you have to define a variable to create a new element when it's much more elegant this way. I haven't been able to find anything online about this. Does anyone know a way for this to work the way I'd like or possibly know why it won't work this way?
回答1:
I'm not sure I understand what you are trying to achieve, but if you want to simply set the HTML of the errorMessage
element to some HTML, why not just using the innerHTML
property?
errorMessage.innerHTML = '<p>Due to an egg allergy, your child will NOT receive the flu vaccine.</p>';
回答2:
appendChild
returns the appended child. So I think you want
var text = "Due to an egg allergy, your child will NOT receive the flu vaccine.";
document.getElementById("errorMessage")
.appendChild(document.createElement('p'))
.appendChild(document.createTextNode(text));
回答3:
If it's something you do more than once, create an abstraction
function createP(text) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(text));
return p;
}
document.body.appendChild(createP('hello world'));
来源:https://stackoverflow.com/questions/36847752/how-to-use-document-createelement-without-defining-a-variable