zoukankan      html  css  js  c++  java
  • JS操作DOM元素

    有两种方式可以修改DOM对象的属性: 
    "."运算符 和 getAttribute(setAttribute)方法。 
    区别如下:

    Html代码 
    1.[div id="test" class="cls" dir="ltr" title="wott" ss="ss"][/div]  
    [div id="test" class="cls" dir="ltr" title="wott" ss="ss"][/div]

    Js代码 
    1.var e = document.getElementById("test");   
    2.//获取属性   
    3.//用 . 来引用,必须是内置的(IE 可以访问自定义属性),而且引用的时候,区分大小写。   
    4.alert(e.id);//"test"   
    5.alert(e.className);//"cls"   
    6.alert(e.ss);//undefined(IE下为 "ss");   
    7.  
    8.//用getAttribute 来引用,可以访问自定义属性,不区分大小写。   
    9.alert(e.getAttribute("id"));//"test"   
    10.alert(e.getAttribute("ID"));//"test"   
    11.//注意浏览器差异   
    12.alert(e.getAttribute("class"));//"cls"(Firefox)   
    13.alert(e.getAttribute("className"));//"cls"(IE)   
    14.  
    15.alert(e.getAttribute("ss"));//"ss"   
    16.  
    17.//设置属性   
    18./*使用 . 运算符和 setAttribute都可以。但是对于自定义属性,使用.运算符的设置的属性无法通过getAttribute获取,反之亦然。*/  
    19.e.setAttribute("abc2","abc2");   
    20.e.abc3 = "abc3";   
    21.  
    22.e.title1 = "abc";   
    23.alert(e.getAttribute("title1"));//null  
    var e = document.getElementById("test");
    //获取属性
    //用 . 来引用,必须是内置的(IE 可以访问自定义属性),而且引用的时候,区分大小写。
    alert(e.id);//"test"
    alert(e.className);//"cls"
    alert(e.ss);//undefined(IE下为 "ss");

    //用getAttribute 来引用,可以访问自定义属性,不区分大小写。
    alert(e.getAttribute("id"));//"test"
    alert(e.getAttribute("ID"));//"test"
    //注意浏览器差异
    alert(e.getAttribute("class"));//"cls"(Firefox)
    alert(e.getAttribute("className"));//"cls"(IE)

    alert(e.getAttribute("ss"));//"ss"

    //设置属性
    /*使用 . 运算符和 setAttribute都可以。但是对于自定义属性,使用.运算符的设置的属性无法通过getAttribute获取,反之亦然。*/
    e.setAttribute("abc2","abc2");
    e.abc3 = "abc3";

    e.title1 = "abc";
    alert(e.getAttribute("title1"));//null


    对于style,className的设置,通常是使用.运算符来实现

    Js代码 
    1.el.style.backgroundColor = "blue";   
    2.el.className = "nav";//works in all browers.  
        el.style.backgroundColor = "blue";
        el.className = "nav";//works in all browers.

    HTMLElement由于继承自Element(继承自Node),因此拥有attributes对象,对属性的访问可以通过它来进行。attributes对象使用一个NamedNodeMap结构用于存放数据,NamedNodeMap本身也是一个"活"的对象,NamedNodeMap对象由Attr节点对象(nodeType = 2)构成。它有以下方法: 
    getNamedItem( name ) — 返回名称为name的Attr对象。 
    removeNamedItem( name ) — 删除名称为name的Attr对象。 
    setNamedItem( node ) — 添加一个Attr对象。 
    item( pos ) — 获取所以为pos的Attr对象。

  • 相关阅读:
    深度解析正则表达式exec和match两者使用的异同以及要注意的地方
    CSS中有关水平居中和垂直居中的解决办法
    Ubunut16.04 安装 Mahout
    正则表达式常用方法
    python字符串判断
    python list
    python一些包
    数据科学中的R和Python: 30个免费数据资源网站
    simple vimrc for python
    python的一些方法
  • 原文地址:https://www.cnblogs.com/daihongyuan/p/5858033.html
Copyright © 2011-2022 走看看