如何用js在页面中添加元素?

JavaScript05

如何用js在页面中添加元素?,第1张

想要在页面动态添加元素,首先要确定在哪个元素后面添加元素,然后利用js的appendChild方法在该元素后面追加元素。

1.获取父节点元素varbody=document.getElementsByTagName('body')[0]。

2.然后动态创建a标签vara=document.createElement('a')。

3.把创建好的a标签追加到body下面body.appendChild(a)。

4.在a标签里面添加文本内容a.innerHTML='这是一个链接'。

5.给a标签添加一个链接a.href='https://www.baidu.com/'。

扩展资料:

js一些原生方法

element.appendChild()方法向节点添加最后一个子节点。

element.innerHTML设置或返回元素的内容。

document.getElementsByTagName()返回带有指定标签名的对象集合。

document.getElementById()返回对拥有指定id的第一个对象的引用。

document.createElement()通过指定名称创建一个元素。

js动态添加数组可以按下面的步骤:

1、在数组的开头添加新元素 - unshift()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.unshift("Lemon","Pineapple")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

<p><b>Note:</b>The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p>

</body>

</html>

测试结果:

Lemon,Pineapple,Banana,Orange,Apple,Mango

2、在数组的第2位置添加一个元素 - splice()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.splice(2,0,"Lemon","Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html> 

测试结果:

Banana,Orange,Lemon,Kiwi,Apple,Mango

3、数组的末尾添加新的元素 - push()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"]

function myFunction()

{

fruits.push("Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html>

测试结果:

Banana,Orange,Apple,Mango,Kiwi