简体   繁体   English

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

[英]How to add a HTML element before a certain HTML element with javascript?

I am trying to add an HTML marquee element before the body element. 我试图在body元素之前添加HTML字幕元素。 I want to achieve this with javascript. 我想用javascript实现。 I have searched all over for a way to do this but no success. 我一直在寻找一种方法来实现此目的,但没有成功。 Please help me. 请帮我。

One way I thought of doing it was 我想到的一种方式是

document.insertBefore('<marquee>', '<body>')

This gives me the error of 这给了我错误

VM888:1 Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.

Please help. 请帮忙。 Thank You! 谢谢!

There are a number of problems with what you're trying to do: 您尝试执行的操作存在许多问题:

  1. The <marquee> element is obsolete ; <marquee>元素已过时 don't use it. 不要使用它。 Ever. 曾经
  2. You shouldn't even be attempting to insert before <body> . 您甚至都不应该尝试<body>之前插入。
    The only valid children of <html> are <head> and <body> , specifically in that order. <html> 的唯一有效子元素是<head><body> ,特别是按此顺序。
  3. Third, you need to insert a DOM node , not an HTML element (a type of node): 第三,您需要插入一个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> 

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM