当前位置: 代码迷 >> 综合 >> JavaScript-获取页面元素的四种常用方法
  详细解决方案

JavaScript-获取页面元素的四种常用方法

热度:22   发布时间:2023-10-25 03:15:02.0

1.根据id获取元素

document.getElementById("id属性的值");

返回值是一个元素对象

案例:点击按钮弹框

<body><input type="button" name="" id="btn" value="button"><script>var btnobj = document.getElementById("btn")btnobj.onclick = function () {alert("OK!");}</script>
</body>

点击按钮后页面弹出提示框。

2.根据标签名字获取元素

document.getElementsByTagName("标签的名字");

返回值是一个伪数组

案例:点击按钮改变多个p标签的文字内容

<body><input type="button" value="button" name="" id="btn"><div id="div1"><p>abcd</p><p>abcd</p><p>abcd</p></div><script>//根据id获取按钮,注册点击事件,添加事件处理函数document.getElementById("btn").onclick = function(){//根据标签名字获取标签var changes = document.getElementById("div1").getElementsByTagName("p");//循环遍历这个数组for(var i=0;i<=changes.length;i++){//每个p标签,设置文字changes[i].innerHTML = "ABCD";}}</script>
</body>

3.根据name属性的值获取元素

document.getElementsByName("name属性的值");

返回值是一个伪数组

案例:点击按钮,改变所有name属性值为name1的文本框中的value属性值

<body><input type="button" value="button" name="" id="btn"><input type="text" value="hello" name="name1" id=""><input type="text" value="hello" name="name1" id=""><input type="text" value="hello" name="name1" id=""><script>//点击按钮,改变所有name属性值为name1的文本框中的value属性值document.getElementById("btn").onclick = function(){//通过name属性值获取元素-------表单的标签var input1 = document.getElementsByName("name1");for(var i=0;i<=input1.length;i++){input1[i].value = "HELLO";}}</script>
</body>

4.根据类样式的名字获取元素 

document.getElementsByClassName("类样式的名字");

返回值是一个伪数组

案例:修改所有文本框的值

<body><input type="button" value="button" name="" id="btn"><input type="text" value="hello" class="text"><input type="text" value="hello" class="text"><input type="text" value="hello" class="text"><script>//点击按钮,改变所有name属性值为name1的文本框中的value属性值document.getElementById("btn").onclick = function(){//通过class属性值获取元素-------表单的标签var input1 = document.getElementsByClassName("text");for(var i=0;i<=input1.length;i++){input1[i].value = "HELLO";}}</script>
</body>

 

  相关解决方案