Javascript选择儿童少年?

时间:2014-10-01 09:53:36

标签: javascript html

Javascript中有没有办法在jQuery中选择子节点的子节点? 例如,我想选择偏移父项所在的<LI>

<li class="all_leagues"> ?

示例:

    <li class="top_leagues">
     <h5>Top Ligen</h5>
     <ul class="games first">
     <ul class="games">
     <ul class="games">
    </li>
    <li class="all_leagues">
     <h5>Alle Ligen</h5>
     <ul class="games first">
      <li id="lg_chk_br_1_l_15231" class="league_check ">
      <li id="lg_chk_br_1_l_15175" class="league_check ">
      <li id="lg_chk_br_1_l_12214" class="league_check ">
    </ul>
    <ul class="games">
      <li id="lg_chk_br_1_l_16106" class="league_check ">
      <li id="lg_chk_br_1_l_13939" class="league_check ">
      <li id="lg_chk_br_1_l_16419" class="league_check ">
    </ul>
    <ul class="games">
      <li id="lg_chk_br_1_l_14823" class="league_check ">
      <li id="lg_chk_br_1_l_11940" class="league_check ">
    </ul>
   </li>

我可以从返回的节点列表中选择id吗? 实际上我得到了li#lg_chk_br_1_l_14481.league_check

2 个答案:

答案 0 :(得分:2)

您可以使用Document.querySelectorAll()

document.querySelectorAll('.all_leagues > ul > li')

注意:Browser compatibility(对于上面的IE8 +应该有用)

或者

&#13;
&#13;
var list = document.querySelectorAll('.all_leagues .league_check');
for (var i = 0, len = list.length; i < len; i++) {
  console.log(list[i].id)
}
&#13;
<ul>
  <li class="top_leagues">
    <h5>Top Ligen</h5>
    <ul class="games first"></ul>
    <ul class="games"></ul>
    <ul class="games"></ul>
  </li>
  <li class="all_leagues">
    <h5>Alle Ligen</h5>
    <ul class="games first">
      <li id="lg_chk_br_1_l_15231" class="league_check "></li>
      <li id="lg_chk_br_1_l_15175" class="league_check "></li>
      <li id="lg_chk_br_1_l_12214" class="league_check "></li>
    </ul>
    <ul class="games">
      <li id="lg_chk_br_1_l_16106" class="league_check "></li>
      <li id="lg_chk_br_1_l_13939" class="league_check "></li>
      <li id="lg_chk_br_1_l_16419" class="league_check "></li>
    </ul>
    <ul class="games">
      <li id="lg_chk_br_1_l_14823" class="league_check "></li>
      <li id="lg_chk_br_1_l_11940" class="league_check "></li>
    </ul>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

好吧我修好了;) 忘了 var list = document.getElementsByClassName("all_leagues")返回一个数组,所以右选择器是 var list = document.getElementsByClassName("all_leagues")[0];

完整代码:

var list = document.getElementsByClassName("all_leagues")[0]; list.getElementsByClassName("league_check ");

反正thx;)