2011-06-14 128 views
6

我一直在尋找在nth-child選擇器中使用nth-child來查找元素。這似乎在Firefox中工作,但似乎沒有在鉻上工作。這是我的測試文件:在Chrome瀏覽器中嵌套nth-child的querySelector看起來不起作用

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>untitled</title> 
    <!--[if IE]> 
     <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
    <![endif]--> 

    <script type="text/javascript" charset="utf-8"> 
     myFunc = function() { 
      if(document.querySelector('#wonderful DIV:nth-child(2) DIV:nth-child(2)')) { 
       alert("found the element"); 
      } else { 
       alert("element not found"); 
      } 
     }; 
    </script> 
</head> 
<body onLoad="myFunc()"> 

    <div id="wonderful"> 
     <div> 
     </div> 
     <div > 
      <div> 
      </div> 
      <div class="blue"> 
       find me! 
      </div> 
     </div> 
    </div> 

</body> 
</html> 

有其他人看到這個問題?有解決方案來解決這個問題嗎?

回答

9

這適用於我在鉻,但它不工作在FF然後。

document.querySelector('#wonderful div:nth-child(2):nth-child(2)') 

兩個瀏​​覽器下面的剪斷的作品,但我相信你已經知道了

document.querySelector('#wonderful div:nth-child(2) div.blue') 

所以看起來Chrome的實施失敗對我來說。

+0

是的,非常有趣。沒有嘗試第一次,但第二次我知道。如果沒有使用XPath,可以使用跨瀏覽器的方式來完成此操作。 – zacharyc 2011-06-14 16:11:21

+0

你的第一個片段沒有意義。嗯,它確實,但':nth-​​child(2):nth-​​child(2)'與':nth-​​child(2)'是一樣的...... – BoltClock 2011-06-14 23:03:48

+0

@BoltClock你是對的,它沒有任何意義,但有用。這就是爲什麼我認爲這是Chrome中的一個實現錯誤。 – DanielB 2011-06-15 07:26:47

相關問題