美文网首页
getAttribute()方法和setAttribute()方

getAttribute()方法和setAttribute()方

作者: LOOK_LOOK | 来源:发表于2016-12-23 20:19 被阅读275次

    getAttribute()方法

    通过元素节点的属性名称获取属性的值。

    语法:

    elementNode.getAttribute(name)

    说明:

    1. elementNode:使用getElementById()、getElementsByTagName()等方法,获取到的元素节点。
    2. name:要想查询的元素节点的属性名字
      看看下面的代码,获取h1标签的属性值:

    运行结果:

    h1标签的ID :alinkh1标签的title :getAttribute()获取标签的属值

    任务:

    试一试,使用getAttribute()方法,完成下面的任务:

    使用getAttribute()方法,获取LI标签的title值。

    案例

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>getAttribute()</title>
    </head>
    <body>   
    <p id="intro">课程列表</p>  
        <ul>  
            <li title="第1个li">HTML</li>  
            <li>CSS</li>  
            <li title="第3个li">JavaScript</li>  
            <li title="第4个li">Jquery</li>  
            <li>Html5</li>  
        </ul>  
    <p>以下为获取的不为空的li标签title值:</p>
    <script type="text/javascript">
        var con=document.getElementsByTagName("li");
        for (var i=0; i< con.length;i++){
         var text=con[i].getAttribute("title");
          if(text!=null)
          {
            document.write(text+"<br>");
          }
        } 
     </script> 
    </body>
    </html>
    

    效果图

    效果图

    setAttribute()方法

    setAttribute() 方法增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。

    语法:

    elementNode.setAttribute(name,value)

    说明:

    1.name: 要设置的属性名。
    2.value: 要设置的属性值。

    注意:

    1.把指定的属性设置为指定的值。如果不存在具有指定名称的属性,该方法将创建一个新属性。
    2.类似于getAttribute()方法,setAttribute()方法只能通过元素节点对象调用的函数。

    任务

    试一试,使用getAttribute()和setAttribute()方法,完成下面的任务:

    (1)使用getAttribute()方法获取元素属性值,保存在变量text。

    (2)使用setAttribute()方法设置title属性值。

    案例

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    </head>
    <body>
      <p id="intro">我的课程</p>  
      <ul>  
        <li title="JS">JavaScript</li>  
        <li title="JQ">JQuery</li>  
        <li title="">HTML/CSS</li>  
        <li title="JAVA">JAVA</li>  
        <li title="">PHP</li>  
      </ul>  
      <h1>以下为li列表title的值,当title为空时,新设置值为"WEB前端技术":</h1>
    <script type="text/javascript">
      var Lists=document.getElementsByTagName("li");
      for (var i=0; i<Lists.length;i++)
      {
        var text=Lists[i].getAttribute("title");
        document.write(text +"<br>");
        if(text=="")
        {
        Lists[i].setAttribute("title","WEB前端技术");
        document.write(Lists[i].getAttribute("title")+"<br>");
        }
      }
    </script>
    </body>
    </html>
    

    效果图

    效果图

    相关文章

      网友评论

          本文标题:getAttribute()方法和setAttribute()方

          本文链接:https://www.haomeiwen.com/subject/uczkvttx.html