深入理解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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...