使用css选择器来获取元素
<!DOCTYPE html>
<html lang=
"en"
>
<head>
<meta charset=
"UTF-8"
>
<meta name=
"viewport"
content=
"width=uluu, initial-scale=1.0"
>
<meta http-equiv=
"X-UA-Compatible"
content=
"ie=edge"
>
<title>使用css选择器来获取元素</title>
</head>
<body>
<ul id=
"ul"
>
<li class=
"red"
>列表项01</li>
<li>列表项02</li>
<li class=
"green"
>列表项03</li>
<li class=
"green"
>列表项04</li>
<li class=
"coral large"
>列表项05</li>
</ul>
<script>
let lists = document.querySelectorAll(
'li'
);
console.log(lists);
lists[0].style.backgroundColor =
'coral'
;
lists.item(2).style.backgroundColor =
'coral'
;
let ul = document.querySelector(
'#ul'
);
console.log(ul);
let li = ul.querySelectorAll(
'.green'
)
for
(
var
i=0; i<li.length;i++){
li[i].style.backgroundColor =
'red'
;
}
</script>
</body>
</html>
根据id属性获取元素
<!DOCTYPE html>
<html lang =
"en"
>
<head>
<meta charset =
"UTF-8"
>
<meta name =
"viewport"
content =
"width=device-width, initial-scale=1.0"
>
<meta http-equiv =
"X-UA-Compatible"
content =
"ie=edge"
>
<title>根据id选择元素</title>
</head>
<body>
<ul id =
"lists"
>
<li id =
"item1"
>列表项01</li>
<li>列表项02</li>
<li id =
"item2"
>列表项03</li>
<li>列表项04</li>
<li id =
"item3"
>列表项05</li>
</ul>
<script>
let item1 = document.getElementById(
'item1'
);
let item2 = document.getElementById(
'item2'
);
let item3 = document.getElementById(
'item3'
);
item1.style.backgroundColor =
'yellow'
;
item2.style.backgroundColor =
'yellow'
;
item3.style.backgroundColor =
'yellow'
;
function
getElements(){
let elements = {};
for
(let i=0;i<arguments.length;i++){
let id = arguments[i];
let elt = document.getElementById(id);
if
(elt ===
null
){
throw
new
Error(
'没有这个元素'
+id);
}
elements[id] = elt;
}
return
elements;
}
let elements = getElements(
'item1'
,
'item2'
,
'item3'
);
console.log(elements);
</script>
</body>
</html>
name属性和标签名获取元素的快捷方式
<!DOCTYPE html>
<html lang=
"en"
>
<head>
<meta charset=
"UTF-8"
>
<meta name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<meta http-equiv=
"X-UA-Compatible"
content=
"ie=edge"
>
<title>name属性和标签名获取元素的快捷方式</title>
</head>
<body>
<img src=
"img/9_13.jpg"
name=
'pic'
>
<form action=
""
name=
"register"
>
<input type=
"text"
placeholder=
"用户名"
>
<input type=
"password"
placeholder=
"密码不少于8位"
>
<button>提交</button>
</form>
<p><a href=
""
>php中文网</a></p>
<script>
</script>
</body>
</html>