深入理解DOM節點類型第五篇——元素節點Element

来源:http://www.cnblogs.com/xiaohuochai/archive/2016/08/29/5819638.html
-Advertisement-
Play Games

[1]特征 [2]子節點 [3]特性操作 [4]attributes屬性 ...


×
目錄
[1]特征 [2]子節點 [3]特性操作[4]attributes

前面的話

  元素節點Element非常常用,是DOM文檔樹的主要節點;元素節點是html標簽元素的DOM化結果。元素節點主要提供了對元素標簽名、子節點及特性的訪問,本文將詳細介紹元素節點的主要內容

 

特征

  元素節點的三個node屬性——nodeType、nodeName、nodeValue分別是1、元素的大寫標簽名和null,其父節點parentNode指向包含該元素節點的元素節點Element或文檔節點Document

  [註意]要訪問元素的標簽名可以使用nodeName,也可以使用tagName屬性,這兩個屬性會返回相同的值

<div id="test">123</div>
<script>
console.log(test.nodeType);//1
console.log(test.nodeName);//'DIV'
console.log(test.nodeValue);//null
console.log(test.parentNode);//<body>
console.log(test.childNodes);//[text]
console.log(test.tagName,test.tagName === test.nodeName);//'DIV' true
</script>

 

子節點

  元素可以有任意數目的子節點和後代節點,因為元素可以是其他元素的子節點。元素的childNodes屬性中包含了它的所有子節點,這些子節點可能是元素、文本註釋、處理指令節點

<ul class="list" id="list">
    <li class="in"></li>
    <li class="in"></li>
</ul>
<script>
var oList = document.getElementById('list');
//IE8-瀏覽器返回2,其他瀏覽器返回5。因為IE8-瀏覽器子節點中不包含空白文本節點
//關於空白文本節點的詳細內容移步至此
console.log(oList.childNodes.length)
</script>

相容

  可以通過檢查nodeType屬性來只獲取元素節點

<ul class="list" id="list">
    <li class="in"></li>
    <li class="in"></li>
</ul>
<script>
var oList = document.getElementById('list');
var children = oList.childNodes;
var num = 0;
for(var i = 0; i < children.length; i++){
    if(children[i].nodeType == 1){
        num++;
    }
}
console.log(num);//2   
</script>

 

特性操作

  每個元素都有一或多個特性,這些特性的用途是給出相應元素或其內容的附加信息。操作特性的DOM方法主要有getAttribute()、setAttribute()、removeAttribute()三個,可以針對任何特性使用,包括那些以HTMLElement類型屬性的形式定義的特性  

getAttribute()

  getAttribute()方法用於取得特性的值,如果給定名稱的特性不存在或無參數則返回null

<div id="test" class="class1"></div>
<script>
console.log(test.getAttribute('class'));//'class1'
console.log(test.getAttribute('title'));//null
console.log(test.getAttribute('b'));//null
console.log(test.getAttribute(''));//null
</script>

  [註意]元素特性和對象屬性並不相同,二者的區別詳細情況移步至此

setAttribute()

  setAttribute()方法接受兩個參數:要設置的特性名和值,如果已經存在,則替換現有的值。如果特性不存在,setAttribute()則創建該屬性並設置相應的值。該方法無返回值

<div id="box">123</div>
<script>
var oBox = document.getElementById('box');
oBox.setAttribute("id","test");
//註意獲取oBox.id時並不會報錯,因為oBox保存的是當時id為box的對象,也就是現在id為test的對象
console.log(oBox.id);//test
</script>

  [註意]通過setAttrbute()方法設置的特性名會統一轉換成小寫形式

<div id="box">123</div>
<script>
var oBox = document.getElementById('box');
oBox.setAttribute("ABC","test");
console.log(oBox.getAttribute("ABC"));//test
console.log(oBox.getAttribute("abc"));//test
</script>

bug

  IE7-瀏覽器設置class、style、for、cellspacing、cellpadding、tabindex、readonly、maxlength、rowspan、colspan、usemap、frameborder、contnenteditable這13個特性沒有任何效果

<style>
.testClass{
    font-size: 30px;
}
</style>    

<div id="box">123</div>
<script>
//IE7-瀏覽器下沒有任何效果,其他瀏覽器出現紅色背景及30px的文字大小
var oBox = document.getElementById('box');
oBox.setAttribute("class","testClass");
oBox.setAttribute("style","height: 100px; background: red;")
</script>     

  可以利用IE7-瀏覽器下對象屬性和元素特性的混淆bug來設置

<style>
.testClass{
    font-size: 30px;
}
</style>    

<div id="box">123</div>
<script>
var oBox = document.getElementById('box');
oBox.setAttribute("class","testClass");
oBox.setAttribute("style","height: 100px; background: red;");
//IE7下oBox.className的值為undefined
if(!oBox.className){
    oBox.setAttribute("className","testClass");
    oBox.style.setAttribute("cssText","height: 100px; background: red;");
}
</script> 

removeAttribute()

  removeAttribute()方法用於徹底刪除元素的特性,這個方法不僅會徹底刪除元素的特性值,還會刪除元素特性。該方法無返回值

<div class="box" id="box"></div>
<script>
var oBox = document.getElementById('box');
console.log(oBox.getAttribute("id"));//box
console.log(oBox.removeAttribute("id"));//undefined
console.log(oBox.getAttribute("id"));//null    
</script>

 

attributes屬性

  元素節點Element是使用attributes屬性的唯一一個DOM節點類型。attributes屬性中包含一個NamedNodeMap,與NodeList類似,也是一個動態的集合。元素的每一個特性都由一個Attr節點表示,每個節點都保存在NamedNodeMap對象中,每個節點的nodeName就是特性的名稱,節點的nodeValue就是特性的值

  attributes屬性包含以下四個方法

getNamedItem(name)

  getNamedItem(name)方法返回nodeName屬性等於name的節點

<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
var oBox = document.getElementById('box');
console.log(oBox.attributes);//NamedNodeMap {0: class, 1: id, 2: name, 3: index, 4: title}
console.log(oBox.attributes.getNamedItem("index"));//index='123'
console.log(oBox.attributes.getNamedItem("index").nodeName);//'index'
console.log(oBox.attributes.getNamedItem("index").nodeValue);//'123'
console.log(oBox.attributes.index);//index='123'
</script>

removeNamedItem(name)

  removeNamedItem(name)方法從列表中移除nodeName屬性等於name的節點,並返回該節點

<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
var oBox = document.getElementById('box');
console.log(oBox.attributes);//NamedNodeMap {0: class, 1: id, 2: name, 3: index, 4: title}
console.log(oBox.attributes.getNamedItem("index"));//index='123'
console.log(oBox.attributes.removeNamedItem("index"));//index='123'
console.log(oBox.attributes.getNamedItem("index"));//null
</script>

setNamedItem(node)

  setNamedItem(node)方法向列表中添加節點,該方法無返回值

<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
var oBox = document.getElementById('box');
console.log(oBox.attributes);//NamedNodeMap {0: class, 1: id, 2: name, 3: index, 4: title}
var oldItem = oBox.attributes.removeNamedItem("index");
console.log(oBox.attributes.getNamedItem("index"));//null
console.log(oldItem);//index='123'
console.log(oBox.attributes.setNamedItem(oldItem));//null
console.log(oBox.attributes.getNamedItem("index"));//index='123'
</script>

item(pos)

  item(pos)方法返回位於數字pos位置處的節點,也可以用方括弧法[]簡寫

<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
var oBox = document.getElementById('box');
console.log(oBox.attributes);//NamedNodeMap {0: class, 1: id, 2: name, 3: index, 4: title}
console.log(oBox.attributes.item(2));//name="abc"
console.log(oBox.attributes[2]);//name="abc"
</script>

遍歷

  attributes屬性主要用於特性遍歷。在需要將DOM結構序列化為HTML字元串時,多數都會涉及遍歷元素特性

function outputAttributes(element){
    var pairs = new Array(),attrName,attrValue,i,len;
    for(i = 0,len=element.attributes.length;i<len;i++){
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        pairs.push(attrName +"=\"" + attrValue + "\"");
    }
    return pairs.join(" ");
}

  針對attributes對象中的特性,不同瀏覽器返回的順序不同

<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
function outputAttributes(element){
    var pairs = new Array(),attrName,attrValue,i,len;
    for(i = 0,len=element.attributes.length;i<len;i++){
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        pairs.push(attrName +"=\"" + attrValue + "\"");
    }
    return pairs.join(" ");
}
//(chrome\safari)class="box" id="box" name="abc" index="123" title="test"
//(firefox)title="test" index="123" name="abc" id="box" class="box"
//(IE8+)title="test" class="box" id="box" index="123" name="abc"
//(IE7-)輸出所有的特性
console.log(outputAttributes(document.getElementById("box")))
</script>

  由上面結果看出,IE7-瀏覽器會返回HTML元素中所有可能的特性,包括沒有指定的特性

specified

  可以利用特性節點的specified屬性來解決IE7-瀏覽器的這個問題。如果specified屬性的值為true,則意味著該屬性被設置過。在IE中,所有未設置過的特性的該屬性值都是false。而在其他瀏覽器中,任何特性節點的specified值始終為true

<div id="box" name="abc" index="123" title="test"></div>
<script>
var oBox = document.getElementById('box');
var yesItem = oBox.attributes.getNamedItem("index");
var noItem = oBox.attributes.getNamedItem("onclick");
//所有瀏覽器瀏覽器都返回true
console.log(yesItem.specified);
//IE7-瀏覽器返回false,而其他瀏覽器報錯,noItem不存在
console.log(noItem.specified);
</script>
<div class="box" id="box" name="abc" index="123" title="test"></div>
<script>
function outputAttributes(element){
    var pairs = new Array(),attrName,attrValue,i,len;
    for(i = 0,len=element.attributes.length;i<len;i++){
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        if(element.attributes[i].specified){
            pairs.push(attrName +"=\"" + attrValue + "\"");    
        }
    }
    return pairs.join(" ");
}
//所有瀏覽器下都返回title="test" class="box" id="box" index="123" name="abc"(順序不一樣)
console.log(outputAttributes(document.getElementById("box")))
</script> 

 

最後

  如果從頭到尾看完這篇博文,會發現全篇篇幅最多的內容是特性的設置。特性設置不是應該在特性節點上嗎?特性節點可以設置,但是使用元素節點來操作特性更方便。元素節點的內容還包括元素節點的操作,但是由於在節點操作博文中已經詳細介紹過,就不再贅述

  下一篇將介紹特性節點

  歡迎交流


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 做為程式員,一直以來沒有自己正式的博客,表示也挺慚愧。做為開發這麼多年,積累實在太少。 現在我要做的,是把平時點滴記錄下來,堅持下去。給自己下達的硬性指標現在是一周至少一篇技術博客吧。 最近沒有研究什麼新的技術,這周的這一篇,姑且先記錄一下現在正在刷的書《JavaScript高級程式設計》吧。 這本... ...
  • × 目錄 [1]特征 [2]屬性 [3]方法 前面的話 元素的特性在DOM中以Attr類型表示,從技術角度講,特性是存在於元素的attributes屬性中的節點。儘管特性是節點,但卻不是DOM節點樹的一部分。本文將詳細介紹該部分內容 特征 特性節點的三個node屬性————nodeType、node ...
  • 讀完 O’Reilly Media 出版的 Web Audio API 第一章對基礎部分做了一些筆記和整理。 ...
  • 1.undefined undefined在js中並不是關鍵字/保留字,因此在IE5.5~8中可以對undefined賦值,但是在IE9以上,對其賦值是無效的 在IE5.5~8中: undefined 1 undefined number 在IE9以上: undefined undefined un ...
  • 原型陷阱: 在處理原型問題上時,我們要註意兩種行為。 1. 當我們對原型對象執行完全替換的時候,有可能會觸發原型鏈的某種異常。 2. prototype.constructor 屬性是不可靠的。 下麵,我們新建一個構造函數,並創建兩個對象: 即使在對象she1和she2對象被創建之後,我們仍然可以對 ...
  • 面向對象 一、編程範式: 1.命令式編程,2.聲明式 命令式編程的思想:面向過程,面向對象。聲明式的思想:DSL(領域特定語言) 命令式編程的定義:告訴電腦以什麼指令來執行代碼。註重中間過程。 聲明式的定義:告訴電腦想要什麼結果就讓電腦自己去執行。不需要關心過程。 面向過程:一步一步的向下執行 ...
  • 一,文本格式化:此例演示如何在一個 HTML 文件中對文本進行格式化。 效果如下: 二,預格式文本:此例演示如何使用 pre 標簽對空行和空格進行控制。 效果如下: 三,“電腦輸出”標簽:此例演示不同的“電腦輸出”標簽的顯示效果。 效果如下: 四,地址:此例演示如何在 HTML 文件中寫地址。 ...
  • 簡單記錄下網站首頁的搭建過程。 背景 自從網站功能變數名稱備案成功下來,一直以來都沒想好首頁應該怎麼寫。其實不是沒想好,而是沒有準備好首頁的多張大背景圖片應該存放在那,畢竟是最廉價的雲伺服器,應該本著勤儉持家的理念,能省就省嘛。不過還好, "bing中文搜索" 官網的背景圖片每天都會更新,於是萌生出了用no ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...