【JavaScript笔记】DOM总结

    技术2022-07-21  77

    自定义属性及getAttribute等方法

    1.getAttribute() 获取特定元素节点属性的值,某些低版本浏览器IE8不支持.

    alert(oBox.getAttribute('title')); alert(oBox.getAttribute('hehe')); alert(oBox.getAttribute('data-name'));

    2.setAttribute() 设置特定元素节点属性的值,某些低版本浏览器IE8不支持.

    oBox.setAttribute('abc', 100);

            3.removeAttribute() 移除特定元素节点属性,某些低版本浏览器IE8不支持.

    oBox.removeAttribute('hehe');

    通过点操作符和中括号添加自定义的属性-低版本IE浏览器可见 - 经常使用

    oBox.num = 1000; oBox.dataAge = 200; oBox['sex'] = '男' console.log(oBox.num, oBox.dataAge, oBox.sex);

    outerHTML、innerHTML、innerText

    var oBox = document.querySelector('.box'); // innerHTML: 读写元素节点里的内容( 包括元素), 从节点起始位置到终止位置的全部内容, 包括内部的元素。 console.log(oBox.innerHTML); // outerHTML: 读写元素节点里的内容( 包括元素), 除了包含innerHTML全部内容外, 还包含元素节点本身。 console.log(oBox.outerHTML); // innerText: 读写某个元素节点的文本内容 console.log(oBox.innerText);

    childNodes节点的集合

    1.childNodes 获取当前元素节点的所有子节点,这里面包含空白节点,但在IE9之前,IE浏览器会自动忽略空白节点.类数组  - 新

    var oUl = document.querySelector('ul'); console.log(oUl.childNodes); console.log(oUl.childNodes[0]);

    2.children 获取当前元素节点的所有子元素,类数组  - 旧

    console.log(oUl.children); console.log(oUl.children[0]);

    3.高级选取:第一个子节点,最后一个子节点,上一个兄弟节点,下一个兄弟节点(包含空白和不包含空白等分成8个属性)

    // firstChild:包含空白节点   // firstElementChild:不包含空白节点 console.log(oUl.firstChild); console.log(oUl.firstElementChild); // lastChild:包含空白节点   // lastElementChild:不包含空白节点 // previousSibling:包含空白节点 // previousElementSibling:不包含空白节点 console.log(oUl.children[2].previousSibling); console.log(oUl.children[2].previousElementSibling); // nextSibling:包含空白节点 // nextElementSibling:不包含空白节点

    节点的高级选取:

    document:获取整个文档对象document

    document.documentElement:获取的html标签元素

    document.title:获取title标题元素

    document.body:获取body标题元素

    parentNode:获取当前节点的父节点


    读写css样式的值

     1.获取css属性值:offsetWidth、offsetHeight、offsetLeft、offsetTop、offsetParent(定位父级);没有单位,不能写入,只能读取。

            offsetLeft/offsetTop:获取元素对象的位置,没有定位也可以读取。

            offsetWidth/offsetHeight:获取元素对象盒模型(包括border和padding)的宽高。

            offsetParent:获取定位父级元素。如果存在定位父级,取到定位父级,否则结果是body元素。       

    console.log(document.querySelector('.box1').offsetParent); //box

    2.获取任意的css属性值:带单位(parseInt)

            2.1.getComputedStyle 标准浏览器 ;格式:window.getComputedStyle(元素对象)[css属性名]       

    var oBox = document.querySelector('.box'); alert(window.getComputedStyle(oBox)['backgroundColor']); //rgb(255, 0, 0) alert(window.getComputedStyle(oBox)['background-color']); //rgb(255, 0, 0) alert(window.getComputedStyle(oBox).backgroundColor); //rgb(255, 0, 0)

            2.2.currentStyle IE浏览器

    alert(oBox.currentStyle['backgroundColor']); //red alert(oBox.currentStyle.backgroundColor); //red

     

    Processed: 0.010, SQL: 9