admin管理员组

文章数量:1332359

I have HTML code structure:

<ul id="main">
 <li>   
    <a href="#"></a>
    <ul>
      <li><a href="#"></a></li>
      <li><a href="#"></a></li>
      <li><a href="#"></a></li>
    </ul>
  <li>
</ul>

Want to select all elements inside UL id="main".

Tried to use:

var el = document.getElementById("main").getElementsByTagName("*");


for (var i=0; i<el.length; i++) {
    alert(el[i].tagName);
}

But only get LI and A tags. UL tags are missing. Any ideas ?

I have HTML code structure:

<ul id="main">
 <li>   
    <a href="#"></a>
    <ul>
      <li><a href="#"></a></li>
      <li><a href="#"></a></li>
      <li><a href="#"></a></li>
    </ul>
  <li>
</ul>

Want to select all elements inside UL id="main".

Tried to use:

var el = document.getElementById("main").getElementsByTagName("*");


for (var i=0; i<el.length; i++) {
    alert(el[i].tagName);
}

But only get LI and A tags. UL tags are missing. Any ideas ?

Share Improve this question edited Jul 16, 2010 at 16:54 Bill the Lizard 406k212 gold badges574 silver badges891 bronze badges asked Jun 21, 2010 at 11:20 BounceBounce 2,1056 gold badges35 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

I get the <ul> tag with your code, give it a test here: http://jsfiddle/RFKsC/1/ (it's the third alert).

So what you have should work, you do need a / in your HTML though, this part:

    </ul>
  <li> <!-- should be </li> -->
</ul>

Without that closing tag, you may get some funky/unpredictable cross-browser behavior, fixing it should resolve the issue.

本文标签: javascriptGet all elements nested in UL tagStack Overflow