2015-01-16 25 views
0

對我的生活中,我無法弄清楚如何使用文本訪問的第一個div「我想這一個」開始DIV1的ID如何使用jQuery訪問div元素2層下來

我嘗試:

$("#div1").first().first().html();

下面是一個例子

<div id="div1"> 
 
    <div class="row"> 
 
    \t <div class="another">I want this one</div> 
 
     <div class="another">Not this one</div> 
 
    </div> 
 
</div>

+1

好,首先你得正確選擇div1。然後,你應該使用正確的jQuery方法。如果你仔細閱讀文檔,清楚地。首先不是你想要的。 –

+0

修復了選擇器..顯然我不會問是否知道:) –

回答

2

嘗試此

1.

$("#div1 .another:first").html(); 

2.

$("#div1 .another").first().html(); 

3.

$("#div1 .another").eq(0).html(); 

Example

+1

請注意,':first'是一個jQuery擴展,因此,如果單獨使用,會更高效。 $(「#div1 .another」)。filter(「:first」)'或'$(「#div1 .another」)。first();'http://api.jquery.com/first-selector/ –

+1

根據http://learn.jquery.com/performance/optimize-selectors/執行'$(「#div1」)。find(「。another」)(其餘的依次)是最快的。 –

+0

感謝您的幫助...完美的作品 –

1

如果你硬是要在第一元素中的第一個元素,您可以使用純JavaScript選擇做一個選擇的性能,像這樣:

var row = $('#div1 > div:first-child > div:first-child'); 
 
alert(row.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="div1"> 
 
    <div class="row"> 
 
    \t <div class="another">I want this one</div> 
 
     <div class="another">Not this one</div> 
 
    </div> 
 
    <div class="row"> 
 
    \t <div class="another">Another one</div> 
 
     <div class="another">Yet another one</div> 
 
    </div> 
 
</div>

相關問題