zoukankan      html  css  js  c++  java
  • DOM

     DOM

     五个常用DOM方法:getElementById、getElementsByTagName、getElemensByClassName、getAttribute、
     setAttribute.

    获取元素

    有3种DOM方法可以获取元素节点,分别是通过元素ID、通过标签名字和通过类名字来获取。

     1.getElementById

    alert(typeof document.getElementById("purchases"));
    

     
    2.getElementsByTagName 

    alert( document.getElementsByTagName("li").length);
    for(var i=0;i<document.getElementsByTagName("li").length;i++){
       alert(typeof document.getElementsByTagName("li")[i]);
     }
    

      
     3.getElementsByClassName

     alert(document.getElementsByClassName("sale").length);
    
     var sales=document.getElementsByClassName("sale");
     var shopping=document.getElementById("purchases");
    

     获取和设置属性

    4.getAttribute

    getAttribute方法不属于document对象,所以不能通过document对象调用。它只能通过元素节点对象调用。例如:可以与getElementsByTagName方法合用,获取每个<p>元素的title属性.

     var paras=document.getElementsByTagName("p");
    for(var i=0;i<paras.length;i++){
      alert(paras[i].getAttribute("title"));
    }
    

     
    5.setAttribute

    setAttribute()有点不同:它允许我们对属性节点的值做出修改。与getAttribute一样,setAttribute
    也只能用于元素节点:

    var shopping =document.getElementById("purchases");
    shopping.setAttribute("title","a list of goods")
    
    alert(shopping.getAttribute("title"));
    

     
    PS:这五个方式是将要编写的许多DOM脚步的基石。

    <style>
     selector{
     properor:value;
     }
     p{
      color:yellow;
      font-family:"arial",sans-serif;
      font-size:1.2em;
     }
     body{
     color:white;
     background-color:black;
     }
     #purchases{
       border:1px solid white;
       background-color:#333;
       color:#CCC;
       padding:1em;
     }
     #purchases li{
     font-weight:bold;
     }
     </style>

     <body>
     <h1>What to buy</h1>
     <p title="a gentle reminder">Don't forget to buy this stuff.</p>
     <ul id="purchases">
      <li>sdfsf</li>
      <li class="sale">sqwe  dfsf</li>
      <li class="sale important">wqqw  sf</li>
     </ul>
     </body>

     


     

  • 相关阅读:
    累加和校验算法(CheckSum算法)
    云锵投资 2021 年 09 月简报
    云锵投资 2021 年 08 月简报
    断言与忽略断言
    出现 undefined reference to `cv::String::deallocate()'的解决方法
    about of string
    esp32: A stack overflow in task spam_task has been detected.
    IDEA部署Tomcat报错:No artifacts marked for deployment
    在safari浏览器上使用php导出文件失败
    laravel中使用vue热加载时 Cannot read property 'call' of undefined BUG解决方案
  • 原文地址:https://www.cnblogs.com/linkhtml/p/6306362.html
Copyright © 2011-2022 走看看