HTML DOM 标头对象
htmlweb developmentfront end technology更新于 2024/5/29 16:44:17
HTML DOM 标头对象与 HTML 5 中引入的 HTML <header> 元素相关联。使用标头对象,我们可以分别使用 createElement() 和 getElementById() 方法创建和访问 <header> 元素。
语法
以下是 − 的语法
创建标头对象 −
var p = document.createElement("HEADER");
示例
让我们看一个 HTML DOM 标头对象的示例 −
<!DOCTYPE html>
<html>
<body>
<h1>Header object example</h1>
<p>Create a header element by clicking the below button</p>
<button onclick="headerCreate()">CREATE</button>
<script>
function headerCreate() {
var h = document.createElement("HEADER");
document.body.appendChild(h);
var h2 = document.createElement("H2");
var txt = document.createTextNode("Header element containing a h2 element is now created");
h2.appendChild(txt);
h.appendChild(h2);
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"创建"按钮时 −

在上面的例子中 −
我们创建了一个 CREATE 按钮,当用户点击该按钮时,它将执行 createHeader() 方法 −
<button onclick="headerCreate()>CREATE</button>
headerCreate() 方法使用 createElement() 方法在 document 对象上创建一个 header 元素,并将其赋值给变量 h。然后,它调用文档主体的 appendChild() 方法,将标题作为子元素附加到文档主体。使用与上面相同的方法,我们使用文档对象的 createTextNode() 方法为其创建一个 <h2> 元素和一个文本节点。
使用 appendChild() 方法将文本节点附加到 <h2> 元素。最后,使用 appendChild() 方法将 <h2> 元素和文本节点作为标题元素的子元素附加 −
function headerCreate() {
var h = document.createElement("HEADER");
document.body.appendChild(h);
var h2 = document.createElement("H2");
var txt = document.createTextNode("Header element containing a h2 element is now created");
h2.appendChild(txt);
h.appendChild(h2);
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

