DOM 的運用
操作元素的屬性
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<script>
window.onload=function()
{
var oTxt=document.getElementById('txt1');
var oBtn=document.getElementById('btn1');
oBtn.onclick=function()
{
//第一種方式
//oTxt.value='asdasdasd' ;
//第二種方式 (任何出現 . 的地方,我們都可以用[]來代替)
//oTxt['value']='123123123';
//第三種方式 DOM的方式
//setAttribute (你要設的名字,你要設的值)
//oTxt.setAttribute('value','999999');
/*
備註:
元素屬性操作三種模式
1. oDiv.style.display="block";
2. oDiv.style["display"]="block";
3. DOM的方式
DOM操作元素的三種方式
1.Get : getAttribute(name);
2.set : setAtribute(name , value) ;
3.Remove: removeAttribute(name);
*/
}
}
</script>
</head>
<body>
<input id="txt1" type="text"/>
<input id="btn1" type="button" value="按鈕"/>
</body>
</html>
DOM的運用
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<script>
function getByClass(oParent,sClass)
{
var aResult=[];
// * : 代表所有的標籤
var aEle=oParent.getElementsByTagName('*');
for (var i = 0 ; i<aEle.length;i++)
{
if (aEle[i].className==sClass)
{
aResult.push(aEle[i]);
}
}
return aResult;
}
window.onload=function()
{
var oUl=document.getElementById('ul1');
var aLi=oUl.getElementsByTagName('li');
/*通過class來尋找我們想要的element*/
/*for (var i = 0 ; i<aLi.length;i++)
{
if (aLi[i].className=='box')
{
aLi[i].style.background='red';
}
}*/
var aBox=getByClass(oUl,'box');
for (var i = 0 ; i<aBox.length;i++)
{
aBox[i].style.background='#CCC';
}
}
</script>
</head>
<body>
<ul id="ul1">
<li class="box"></li>
<li class="box"></li>
<li class="box"></li>
<li></li>
<li></li>
<li></li>
<li class="box"></li>
<li></li>
</ul>
</body>
</html>