JS获取节点

JS 的 document 内置对象
  把 html 中每个标签看成一个节点, 通过 js 将这些节点获取出来
  使用 JS 的 document 内置对象(对象有自己的属性和方法),
  内置对象就是已经创建好的对象, 我们只需要直接使用即可

方法:
  document.getElementById("id属性")
    根据元素的 id 值获取对象, 返回值是一个对象
  innerHTML
    获取节点对象下 的所有 html 代码.
  document.getElementsByTagName("标签名");
    根据标签吗获取对象, 返回一个集合(数组)
  isNaN(字符串)
    判断一个字符串是否是纯数字, 不是纯数字返回true, 反之返回 false

Demo: 根据 id 值获取元素节点对象
html:

1 <body>
2         <div id = "div1">
3             <p>
4                 很快就放假了!
5             </p>
6         </div>
7 </body>
8 </html>
9 <script src="index.js"></script>

js:

var node = document.getElementById("div1");
console.log(node.innerHTML);

Demo: 根据标签名获取元素节点
html:

<body>
    用户名: <input type="text" name="username" value="张三">
     密 码 : <input type="password" name="pwd" value="1234">
     电 话 : <input type="text" name="iphone" value="110">
</body>
</html>
<script src="index.js"></script>

js:

 1 var inputs = document.getElementsByTagName("input");
 2 console.log("用户名: " + inputs[0].value);
 3 console.log(" 密 码: " + inputs[1].value);
 4 var iphone = inputs[2].value;
 5 //判断一个字符串是否是纯数字
 6 if (isNaN(iphone)){ //不是纯数字返回true, 是纯数字返回false
 7     alert("电话不是纯数字")
 8 }else{
 9     alert("电话是纯数字")
10 }

Demo: 根据 class 获取元素节点
html:

<body>
        <p class="wuyi">
            <h1>1.五一快乐</h1>
        </p>
        <p class="wuyi">
            <h1>2.五一快乐</h1>
        </p>
        <p class="wuyi">
            <h1>3.五一快乐</h1>
        </p>
        <p class="wuyi">
            <h1>4.五一快乐</h1>
        </p>
</body>
</html>
<script src="index.js"></script>

js:

var ps=document.getElementsByClassName('wuyi');
//遍历循环 ps
for(var i=0;i<ps.length;i++){
    console.log(ps[i]);
}

Demo: 在文本框输入两个数, 然后计算出值之后输出
html:

<body>
    A的值: <input type="text" name="numA">
    B的值: <input type="text" name="numB">
    A的值: <input type="text" name="numC">
    <button type="button" onclick="addSum()">开始计算</button>
</body>
</html>
<script src="index.js"></script>

js:

 1 function addSum(){
 2     //获取文本框中的值
 3     var inputs=document.getElementsByTagName('input');
 4     var numA=inputs[0].value;
 5     var numB=inputs[1].value;
 6     //将字符串换成数字
 7     var sum=parseInt(numA)+parseInt(numB);
 8     //将计算的值填写到第三个input中
 9     inputs[2].value=sum;
10 }

猜你喜欢

转载自www.cnblogs.com/yslf/p/10780260.html