开发者

ul's within ul's dom navigation code just a little off

    <body>
    <ul class="outer">

        <li>This is info for Chino in Reno</li>
        <li>  
            <ul class="inner">
                <li>This is info for Chino in Reno</li>
            </ul>
        </li>
        <li>
            <ul class="inner">
                <li>This is info for Chino in Reno</li>
            </ul>
        </li>
        <li>This is info for Chino in Reno</li>
        <li>
            <ul class="inner">
                <li>This is info for Chino in Reno</li>
            </ul>
        </li>
        <li>This is info for Chino in Reno</li>
    </ul>
    </body>

<script type="text/javascript">
    var items = document.getElementsByClassName("outer");//ul = "outer"
    for (i = 0, ii = items.length; i < ii; i++)// go through the children "outer"
    {
        var outer_list = items[i].getElementsByTagName("li");

        for (j = 0, jj = outer_list.length; j < jj; j++)
        {开发者_运维百科
            if(outer_list[j].childNodes)// want to get nested li < ul 
            {
                outer_list[j].className = "style2"; // style it green
            }
            else
            {
                outer_list[j].className = "style"; // style it red
            }
        };// end for loop
    };

I'm trying to experiment and extend this code for ul's within li's within a ul!

I feel like that if statement is where things aren't sound, perhaps I have the wrong the childNode method???

perhaps this would be better, but I don't quite know how to write it out:

if(outer_list[j].hasChildNodes == true)

Any suggestions?


You don't actually say what your desired result is, or what is going wrong, but I think you'll find this line:

var outer_list = items[i].getElementsByTagName("li"); 

isn't doing what you think because getElementsByTagName() returns all descendents matching the specified tag, not just direct children.

Regarding the if statement you mention that uses childNodes, assuming your intention is to test whether the element has any children try changing it to this:

if(outer_list[j].childNodes.length > 0)

Note: CSS selectors can handle these types of nested lists without the need for JavaScript.


As nnnnnn says, you can use CSS. It can be resonably independant of the document structure and doesn't require any script, e.g.:

<style type="text/css">
  ul { background-color: blue;}
  ul ul { background-color: green;}
  ul ul ul { background-color: red;}
</style>

<ul>
  <li>This one is blue
    <ul>
      <li>This one is green
        <div>Intervening element
          <ul>
            <li>This one is red
          </ul>
        </div>
    </ul>
    <li>Another blue one
</ul>

That will work on all ULs and different structures (like the DIV above). There are ways of doing it in script, but only if the CSS method isn't suitable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜