js 获取元素的几种方法

获取 元素/节点/标签 的几点方法

getElementById

getElementsByTagName

getElementsByName

getByClass √               // 现在通过class 也可以查找节点

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>getByClasss</title>
<script type="text/javascript">
function getByClass(oParent, aClass)
{
    var aEle=oParent.getElementsByTagName('*');
    var arr=[];
    for(var i=0;i<aEle.length;i++)
    {
        if(aEle[i].className==aClass)
        {
            arr.push(aEle[i]);
        }
    }
    return arr;
}
window.onload=function()
{
    var oUl=document.getElementById('ul1');
    var aBox=getByClass(oUl, 'box');
    for(var i=0;i<aBox.length;i++)
    {
        aBox[i].style.background="red";
    }
}
</script>
</head>

<body>
<ul id="ul1">
    <li></li>
    <li class="box">a</li>
    <li></li>
    <li></li>
    <li class="box">a</li>
    <li></li>
</ul>
</body>
</html>

 

posted @ 2013-02-25 16:37  Daya  阅读(4861)  评论(0编辑  收藏  举报