使用clasname找出特定的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
//找出父元素下特定的子元素函数
function getByClass(oParsent,oclass){
//选择父节点下面的所有元素节点
var oEle = oParsent.getElementsByTagName('*');
var aResult =[];
for(var i= 0;i<oEle.length;i++){
if(oEle[i].className == oclass){
aResult.push(oEle[i]);
}
}
return aResult;
}
//将找出来的子元素改变颜色
window.onload = function(){
var oUl = document.getElementById('ul1');
var aBox = getByClass(oUl,'box');
alert(aBox.length);
for (var i=0;i<aBox.length;i++) {
aBox[i].style.background = 'red';
}
}
</script>
</head>
<body>
<ul id="ul1">
<li class="box"></li>
<li></li>
<li class="box"></li>
<li></li>
<li></li>
</ul>
</body>
</html>
JS中dom的元素获取
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 200px;
height: 200px;
background: #CCCCCC;
margin: 100px;
position: relative;
}
#div2{
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 50px;
top: 50px;
}
</style>
<script>
window.onload = function(){
oUl = document.getElementById('ul1');
//这个循环是找出childnodes中的有效元素
for (var i = 0;i<oUl.childNodes.length;i++) {
if(oUl.childNodes[i].nodeType==1 )
{
oUl.childNodes[i].style.background ='red';
}
}
//直接用children找出有效元素,不用判断,和上面的循环作用一致.
for (var i=0;i<oUl.children.length;i++) {
oUl.children[i].style.background='red';
}
//设置点击事件,将a元素所在的li隐藏
oAl = document.getElementsByTagName('a');
for (var i =0;i<oAl.length;i++) {
oAl[i].onclick = function(){
this.parentNode.style.display = 'none';
}
}
//查看相对父元素的位置偏移,offsetParent用来定位参考的父元素
// var oDiv2= document.getElementById('div2');
// alert(oDiv2.offsetParent);
//firstElementChild兼容性问题
if(oUl.firstElementChild ){
oUl.firstElementChild.style.background='red';
}else
{
oUl.firstChild.style.background = 'red';
}
}
</script>
</head>
<body>
<ul id="ul1">
<li><a href="javascript:;">隐藏</a></li>
<li><a href="javascript:;">隐藏</a></li>
<li><a href="javascript:;">隐藏</a></li>
<li><a href="javascript:;">隐藏</a></li>
<li><a href="javascript:;">隐藏</a></li>
<li><a href="javascript:;">隐藏</a></li>
</ul>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>
dom简单的插入和删除
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function(){
var oBtn = document.getElementById('btn1');
var oText = document.getElementById('text1');
var oUl = document.getElementById('ul1');
var oLi = oUl.getElementsByTagName('li');
//删除函数,有一个问题,删除怎么删不了
// function deleteRow(deleNum){
// oLi.removeChild(deleNum.parentNode);
// }
//点击函数
oBtn.onclick = function(){
var aLi = document.createElement('li');
aLi.innerHTML =oText.value+'\t'+"<input type ='button' value ='删除' onclick='deleteRow(this)'></input>";
if(oLi.length>0)
{
oUl.insertBefore(aLi,oLi[0]);
}else
{
oUl.appendChild(aLi)
}
}
}
</script>
</head>
<body>
<input type="text" id="text1" />
<input type="button" id="btn1" value="插入" />
<ul id="ul1"></ul>
<a class="box"></a>
</body>
</html>