簡體   English   中英

如何使用javascript在某個HTML元素之前添加HTML元素?

[英]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'.

請幫忙。 謝謝!

您嘗試執行的操作存在許多問題:

  1. <marquee>元素已過時 不要使用它。 曾經
  2. 您甚至都不應該嘗試<body>之前插入。
    <html> 的唯一有效子元素是<head><body> ,特別是按此順序。
  3. 第三,您需要插入一個DOM 節點 ,而不是HTML元素 (一種節點):

 // 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM