[英]Insert element in html using java script
I'm trying to insert a button into my html using javascript, I read this tutorial : javascript.info/tutorial/modifying-document and made this simple example to test it : jsfiddle.net/XuAfA/86/ but it's not working ... Here is the code of the example if you don't want to open the url : 我试图使用javascript将按钮插入到html中,我阅读了本教程: javascript.info/tutorial/modifying-document,并制作了一个简单的示例进行测试: jsfiddle.net/XuAfA/86/,但是它没有用。 ..如果您不想打开url,这是示例代码:
var bibi = document.getElementById('bibi');
var s = document.createElement('button');
s.innerHTML = "toto";
document.insertBefore(s, bibi);
and my html : 和我的html:
<ul id="Parent">
<button id="bibi"> hello wrold ! </button>
</ul>
I can't see why this is not working 我不明白为什么这不起作用
insertBefore
is executed on the parent element of the element you want to insert before insertBefore
在要插入的元素的父元素上执行
parent.insertBefore(toInsert, child);
As the document contains the body which contains the elements etc. you can't use document
as the parent element, you should be doing 由于文档包含包含元素等的主体,因此不能将document
用作父元素,您应该这样做
bibi.parentNode.insertBefore(s, bibi);
Next code explains the difference between INNERHTML and CREATE ELEMENT to add a button : 下面的代码解释了INNERHTML和CREATE ELEMENT之间添加按钮的区别:
<html>
<head>
<title>Insert element</title>
<script type="text/javascript">
function btn_inner () {
var bibi = document.getElementById( 'bibi' );
bibi.innerHTML = "<input type='button' value='I was created with INNERHTML ! ! !' />";
}
function btn_create () {
var bibi = document.getElementById( 'bibi' );
var obj;
obj = document.createElement( "input" );
obj.type = "button";
obj.value = "I was created with CREATE ELEMENT ! ! !";
bibi.appendChild( obj );
}
</script>
</head>
<body>
<button onclick="btn_inner()">Click here to insert button with INNERHTML</button>
<button onclick="btn_create()">Click here to insert button with CREATE ELEMENT</button>
<br/>
<br/>
<div id="bibi"></div>
</body>
</html>
Create a textfile, rename it TEST.HTML (or any name), then copy-paste previous code, save the file and double click it to open it in a browser. 创建一个文本文件,将其重命名为TEST.HTML(或任何名称),然后复制粘贴先前的代码,保存该文件并双击以在浏览器中将其打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.