How to use document.createElement() without defining a variable

拟墨画扇 提交于 2020-01-07 09:02:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!