通过JavaScript动态创建和打印h1标签

8

我希望能够在JavaScript中创建一个函数,只需键入h1("hello")即可打印出hello。

我想避免使用这种方法:

function h1(text) {
    document.write('<h1>'+text+'</h1>');
}

这是我所拥有的:

function h1(text) {
    var div = document.createElement('div');
    document.appendChild(div);
    var h1 = document.createElement('h1');
    div.appendChild(h1);
    h1.createTextNode(text);
}

2
那么,你手头的东西有什么能/不能工作? - Lee Taylor
3个回答

22
<script>
function myFunction(text) {
    var h = document.createElement("H1");
    var t = document.createTextNode(text);
    h.appendChild(t);
    document.body.appendChild(h);
}
</script>

5
你不需要使用 div,而且你需要将其附加到 document.body 而不是 document。此外,元素没有 createTextNode 方法,该方法在 document 上:
function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}

实时示例:

function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}
var counter = 0;
var timer = setInterval(function() {
  ++counter;
  h1("Hi #" + counter);
  if (counter == 5) {
    clearInterval(timer);
  }
}, 500);

更多探索:


1
更好的方式是导入 ElementsJS,然后只需引用其中的每个元素。

// Create H1 Without Class
var root = document.getElementById("root");
create_element('h1',null, root, "This is a H1 Text");


// Create H1 With Class
var root = document.getElementById("root");
create_element('h1',{'class':'h1css'}, root, "This is a H1 Text");
.h1css {
  background-color : grey;
  height: 50px;
  position: absolute;
  }
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接