当前位置: 代码迷 >> 综合 >> 如何获取HTML元素对应JavaScript对象
  详细解决方案

如何获取HTML元素对应JavaScript对象

热度:39   发布时间:2024-01-29 11:09:02.0

四种方法:

1.通过id获取

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title></head><body><div id="ch"><span>长城</span><b>故宫</b></div><p class="zh">黄河</p><p class="zh">黄河</p><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><script>var element = document.getElementById("ch");/*获取id为"ch"的元素对应的JavaScript对象*/console.log(element);</script></body>
</html>

2.通过class名获取:

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title></head><body><div id="ch"><span>长城</span><b>故宫</b></div><p class="zh">黄河</p><p class="zh">黄河</p><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><script>var elements = document.getElementsByClassName("zh");for (var i in elements) {console.log(elements[i]);/*由于class名可以有多个,则可以用数组遍历,(加强for循环)*/}</script></body>
</html>

3.通过标签名获取:

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title></head><body><div id="ch"><span>长城</span><b>故宫</b></div><p class="zh">黄河</p><p class="zh">黄河</p><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><script>elements = document.getElementsByTagName("p");for (var i in elements) {console.log(elements[i]);}</script></body>
</html>

4.通过name值获取:

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title></head><body><div id="ch"><span>长城</span><b>故宫</b></div><p class="zh">黄河</p><p class="zh">黄河</p><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><input type = "checkbox" name="hobby"/><script>elements = document.getElementsByName("hobby");for (var i in elements) {console.log(elements[i]);}</script></body>
</html>

 

  相关解决方案