如何在javascript中获取后代

时间:2013-06-07 18:14:18

标签: javascript

我想要的每个人都在div下使用类“a1”获取所有p元素,类为“oshow”,在类“pro_line”下为agian而不使用javascipt中的getelementsbyclassname

 <div id="Zi03">
    <div class="ye">text</div>
    <div class="yee">text</div>
    <div class="pro-line">
         <div class="oshow">
         <div class="compic"><a href="#"></a></div>
         <p class="a1"><a href="poduct"></a></p>
         <p class="a2"><a href="poduct"></a></p>
         <div class="a3"><a href="poduct"></a></div>
        </div> 
         <div class="oshow">
         <div class="compic"><a href="#"></a></div>
         <p class="a1"><a href="poduct"></a></p>
         <p class="a2"><a href="poduct"></a></p>
         <div class="a3"><a href="poduct"></a></div>
        </div>
         <div class="oshow">
         <div class="compic"><a href="#"></a></div>
         <p class="a1"><a href="poduct"></a></p>
         <p class="a2"><a href="poduct"></a></p>
         <div class="a3"><a href="poduct"></a></div>
        </div> ...
        ....
        ....
    </div>
 </div>

请有人帮助我如何在不使用getelementsbyclassname的情况下在javascript中获取它,但我可以按ID使用

提前多多感谢....

3 个答案:

答案 0 :(得分:1)

您可以对getElementsByClassName()现代浏览器使用以下替换方法:

function getElementsByClassName(node, classname) {
        /// <summary>
        /// Replaces built-in function of modern browser. Implemented because not supported by IE7/8
        /// </summary>
        /// <param name="node">DOM element withing which search is done</param>
        /// <param name="classname">String with class name for search</param>
        /// <returns type="">Array of found elements</returns>

        var a = [];
        var re = new RegExp('(^| )' + classname + '( |$)');
        var els = node.getElementsByTagName("*");
        for (var i = 0, j = els.length; i < j; i++)
            if (re.test(els[i].className)) a.push(els[i]);
        return a;
    }

用以下内容称呼它:

var aElems = getElementsByClassName(document.getElementById('Zi03'),'pro-line')

答案 1 :(得分:0)

var elem = document.getElementById('Zi03');
var proline = elem.children[2];

For loop for all immediate childs of proline 
   var oshow= proline.firstElementChild;
   var a1 = show.children[1]
   //display a1 Or whatever you want
End 

如果a1和其他元素处于相同的层次结构

,则此方法有效

答案 2 :(得分:0)

这是一个让你入门的版本,它并不完美,但你可以改进它

var nodes = [];
var allChildNodes = document.getElementById('Zi03').getElementsByTagName('*');
for  (var i = 0; i < allChildNodes.length); i++ ) {
    var isA1 = ;
    var isUnderProline =  allChildNodes[i].parentNode.className == 'pro-line';
    var isUnderOShow = allChildNodes[i].parentNode.parentNode.className == 'oshow';

    if (
            allChildNodes[i].className == 'a1' &&
            allChildNodes[i].parentNode.className == 'pro-line' &&
            allChildNodes[i].parentNode.parentNode.className == 'oshow'  

       ){
       nodes.push(allChildNodes[i]);
    }
}