[英]How to display the innerHtml contents of newly created element
function Eval(a){
var element= document.createElement('p'); // Creating a paragraph
$(element).addClass("output-class");
element.innerHTML+= a; }
The contents added are not displayed even after styling "output-class" dynamically or even within tag. 即使在动态设置“输出类”样式之后,甚至在标记内也不会显示添加的内容。 But if I write console.log(element) then I get the required result but not on the webpage. 但是,如果我编写console.log(element),则会得到所需的结果,但不在网页上。
You almost there, three main considerations: 您快到了,主要考虑三点:
classList
instead. 您不需要jQuery来添加类名,而应使用classList
。 element.innerHTML += a;
您不需要使用此语句element.innerHTML += a;
because this is a newly created element, so the innerHTML
attribute is empty. 因为这是一个新创建的元素,所以innerHTML
属性为空。 Use this element.innerHTML = a;
使用此element.innerHTML = a;
instead 代替 appendChild
. 为此,请使用函数appendChild
。 In this example, the parent is the body element. 在此示例中,父级是body元素。
function Eval(a, parent) { var element = document.createElement('p'); // Creating a paragraph element.classList.add("output-class"); element.innerHTML = a; parent.appendChild(element); } Eval('Ele from SO', document.body)
.output-class { font-size: 24px }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.