嘿嘿,趁熱打鐵,把之前總結(jié)的東西整理整理貼一貼,對于DOM部分重要的
1. 獲取元素
1.1 通過屬性獲取元素
document.body
document.documentElement
body,html只能從document下被獲取到
[SelectElement].options
獲取某個select下的一組options
[FormName]
[FormName][InputName]
獲取一個name="formName"的form元素, 還獲取啥! 這就是變量名直接用就行啦
獲取一個……誒嘛這還用說么
有一點需要注意,在使用最后一種方式獲取元素時,如果被定位的表單元素為一則返回一個元素(不是數(shù)組),如果表單元素為多個則返回一組元素
1.2 通過方法獲取元素
document.getElementById()
該方法只能從document下獲取id屬性為對應(yīng)參數(shù)的單個元素
document.getElementsByName()
該方法只能從document下獲取name屬性為對應(yīng)參數(shù)的一組元素
[Element].getElementsByTagName()
獲取標(biāo)簽名為對應(yīng)參數(shù)的一組元素
[Element].getElementsByClassName()
返回class屬性中包含對應(yīng)參數(shù)的一組元素 IE8+
[Element].querySelector()
返回一個元素 IE8+ 用法類似JQuery
[Element].querySelectorAll()
返回一組元素 IE8+ 用法類似JQuery
通過class獲取元素的封裝函數(shù),為了兼容IE8以下瀏覽器
話說這年頭還有用自己封的函數(shù)解決兼容問題么,大jquery不是力抗泰山了么 =。= ,不想看就別看了。
function getByClass(parent, classStr) {
if(parent.getElementsByClassName) {
return parent.getElementsByClassName(classStr)
}
else {
var arr = []
var elements = parent.getElementsByTagName('*')
var hasClass = false
for(var i = 0; i<elements.length; i++) {
var tmp = element[i].class.split(/\s+/)
for(var j = 0; j<tmp.length; j++) {
if(classStr === tmp[i]) hasClass = true
}
if(hasClass) arr.push(element[i])
}
}
return arr
}
2. 創(chuàng)建元素
2.1 通過屬性創(chuàng)建元素
[element].innerHTML
// eg:
div.innerHTML = '<h1>Hello</h1>'
該屬性被賦予的值會直接渲染到頁面上,對單標(biāo)簽元素?zé)o效
2.2 通過方法創(chuàng)建元素
document.createElement()
只有document元素可以使用該方法,參數(shù)是你想創(chuàng)建的標(biāo)簽名。不過我們還需要調(diào)用 [element].appendChild(createElement) 方法將創(chuàng)建好的元素插入到DOM??中
3. 元素的屬性
3.1 一般屬性
一般的屬性值我們都可以通過 . 運算和 [] 運算來獲取到,例如
<html>
<a id="link" href="http://www.lxweimin.com/"></a>
</html>
<script>
document.getElementById('link').href
// => "http://www.lxweimin.com/"
</script>
我們還可以通過一些方法來操作自定義屬性,當(dāng)然他們對一般屬性也是有效的
[Element].getAttribute([attributeName])
[Element].setAttribute([attributeName],[attributeValue])
[Element].removeAttribute([attributeName])
需要說明的有特殊的幾個
3.2 [Element].className
className實際上就是元素的class,我們可以通過直接修改他的值來改變class
div.className = 'col-xs-6 col-md-4'
也可以通過[element].classList返回的類數(shù)組進行操作,這個屬性只在ie10以上的瀏覽器才被支持
div.classList
// => ['col-xs-6', 'col-md-4']
div.classList.add('col-offset-2')
// => ['col-xs-6', 'col-md-4', 'col-offset-2']
div.classList.remove('col-md-4')
// => ['col-xs-6', 'col-offset-2']
div.classList.contains('col-xs-6')
// => true
3.3 [Element].style
通常我們會得到一個名為 CSSStyleDeclaration 的對象,最基礎(chǔ)最直接的DOM操作是通過修改它來完成的
div.style.color = 'orange'
就這樣,當(dāng)我們使用 CSSStyleDeclaration 這個對象的時候,還有一個神奇的功能,我們在行內(nèi)設(shè)置的樣式會被添加到這個對象中并附上索引值,如
<html>
<div style="width: 100px; color: red">
</html>
<script>
</script>
這個對象里面的屬性值大概變態(tài)多到300+,囊括了所有的樣式在內(nèi),有的我也不知道有個鳥用,大家閑著蛋疼可以擼擼文檔