[英]How to add a HTML element before a certain HTML element with javascript?
我試圖在body元素之前添加HTML字幕元素。 我想用javascript實現。 我一直在尋找一種方法來實現此目的,但沒有成功。 請幫我。
我想到的一種方式是
document.insertBefore('<marquee>', '<body>')
這給了我錯誤
VM888:1 Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.
請幫忙。 謝謝!
您嘗試執行的操作存在許多問題:
<marquee>
元素已過時 ; 不要使用它。 曾經 <body>
之前插入。 <html>
的唯一有效子元素是<head>
和<body>
,特別是按此順序。 // Create the node to insert var newNode = document.createElement("span"); newNode.innerHTML = 'new'; // Set up the other nodes var parent = document.getElementById("childElement").parentNode; var child = document.getElementById("childElement"); // Insert it parent.insertBefore(newNode, child);
<div id="parentElement"> <span id="childElement"> existing</span> </div>
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.