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对象。

  • 相关阅读:
    JavaScript对原始数据类型的拆装箱操作
    Javascript继承(原始写法,非es6 class)
    动态作用域与词法作用域
    自行车的保养
    探索JS引擎工作原理 (转)
    C语言提高 (7) 第七天 回调函数 预处理函数DEBUG 动态链接库
    C语言提高 (6) 第六天 文件(续) 链表的操作
    C语言提高 (5) 第五天 结构体,结构体对齐 文件
    C语言提高 (4) 第四天 数组与数组作为参数时的数组指针
    C语言提高 (3) 第三天 二级指针的三种模型 栈上指针数组、栈上二维数组、堆上开辟空间
  • 原文地址:https://www.cnblogs.com/daihongyuan/p/5858033.html
Copyright © 2011-2022 走看看