To manipulate an element, the steps are: (改变网址)
选择一个元素:document.querySelector();
将reference存储在变量中
: let link = document.querySelector(‘a’);
改变属性: link.herf = ’https://some.website.url/’;
link.textContent = ‘UCD Website’;
querySelectorAll(): 一个 NodeList 对象,表示文档中匹配指定 CSS 选择器的所有元素。
// 获取文档中所有的 <p> 元素 var x = document.querySelectorAll("p");
// 设置第一个 <p> 元素的背景颜色 x[0].style.backgroundColor = "red";
getElementsByTagName() 方法可返回带有指定标签名的对象的集合。
var x=document.getElementsByTagName("input");
alert(x.length);
下面的代码可以获得文档中的第四个段落:
var myParagragh = document.getElementsByTagName("p")[3]
;
document.getElementById():let myVar = document.getElementById(“firstpara”);
Steps involved in creating new nodes
▪ Select the parent node, using document.querySelector();
▪ Create a new element using document.createElement();
▪ Give it some content (say, textContent, value or href or any other property)
▪ Append new element to the parent node using appendChild()
<script>
let firstpara = document.querySelector(‘#firstpara’);
let newheading = document(‘h5’);
newheading.textContent = ‘A new heading’;
firstpara.appendChild(newheading);
</script>
改变元素位置
- Get the node you want to remove
- Get a new parent node
- appendChild to the parent
<script>
Let firstpara = document.querySelector(‘#firstpara’);
Let section = document.querySelector(‘section’);
Section.appendChild(firstChild);
</script>
删除元素:
- find the node
- delete itself
let firstpara = document.querySelector(‘#firstpara’);
firstpara.remove();
删除下拉框中的选项:
var parent = document.querySelector('#colorSelect');
parent.remove(parent.selectedIndex);