document.getElementById/Name/TagName

document.getElementById  

1、getElementById

作用:一般頁面裏ID是唯一的,用於準備定位一個元素 
語法: document.getElementById(id) 
參數:id :必選項爲字符串(String) 
返回值:對象; 返回相同id對象中的第一個,按在頁面中出現的次序,如果無符合條件的對象,則返回 null

example:
document.getElementById("id1").value;

2、getElementsByName

作用:按元素的名稱查找,返回一個同名元素的數組
語法: document.getElementsByName(name)
參數:name :必選項爲字符串(String)
返回值:數組對象; 如果無符合條件的對象,則返回空數組,按在頁面中出現的次序
注意:返回數組值爲value屬性的值,
            如果某標籤無value屬性,當你添加上value屬性並賦值後,getElementsByName也能取到其值,
            當未對value屬性賦值時,  getElementsByName返回數組值將是undefined ,
            但仍能獲得相同name標籤的個數document.getElementsByName(name).length
            當未設置name屬性時document.getElementsByName仍能使用,它將根據你id取得value屬性的值

example:
document.getElementsByName("name1")[0].value;  
document.getElementsByName("name1")[1].value;
<span id='CBylawIndexName' class='normalNode' value='all' >全部</span>"
<span id='CBylawIndexName' class='normalNode' value='ALL' >全部</span>"
span標籤其實沒有name和value屬性
但document.getElementsByName("CBylawIndexName")仍將取得value的值

3、getElementsByTagName

作用:按HTML標籤名查詢,返回一個相同標籤元素的數組
語法: object.getElementsByTagName(tagname) object可以是document或event.srcElement.parentElement等
參數:tagname:必選項爲字符串(String),根據HTML標籤檢索。
返回值:數組對象; 如果無符合條件的對象,則返回空數組,按在頁面中出現的次序

example:
document.getElementsByTagName("p")[0].childNodes[0].nodeValue;  
document.getElementsByTagName("p")[1].childNodes[0].nodeValue
發佈了27 篇原創文章 · 獲贊 8 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章