html如何選擇兒童元素?
<div class="one">
<div class="two">
<div class="three">text</div>
</div>
</div>
如何選擇兒童元素。我試過這個。
$('.one').children('.three').css('color','#f00');
我知道.find()函數,但想知道另一種方法。
html如何選擇兒童元素?
<div class="one">
<div class="two">
<div class="three">text</div>
</div>
</div>
如何選擇兒童元素。我試過這個。
$('.one').children('.three').css('color','#f00');
我知道.find()函數,但想知道另一種方法。
嘗試這些線路之一:
$('.one').children().children('.three').css('color','#f00');
$('.one').children('.two').children('.three').css('color','#f00');
$('.one').children('.two').find('.three').css('color','#f00');
希望它會幫助你。
你也可以這樣做:
$('.one > .two').children('.three').css('color','#f00');
當然還是:
$('.one > .two > .three').css('color','#f00');
這裏是一個小提琴:http://jsfiddle.net/3nhrh/1/
請在發帖前仔細閱讀問題 – musefan
@musefan夠了:)編輯:) –
你可以隨時更改選擇器鏈一起上課:
$(".one .three").css("color", "#f00");
這將選擇具有類.three
您可以使用上下文選擇的.one
類的任何子女:
$('.three', $('#one')).css(.....
這是錯誤的.....','不應該有 –
@DKM謝謝。固定。 – Abhitalks
以下方法可能會幫助您:
var children=$('.one').children();
children.each(function(idx, val){
$(this).css('color','#f00');
});
嘗試
$('.one > div.three').css('color','#f00');
試試這個... jsfiddle
$("div").children(".two").css("color", "blue");
這一切都取決於正是你想要達到的目標。
如果在文檔中只存在一次「three」類的項目(或者想要獲取所有項目),則可以使用$('.three')
。
,如果你正在尋找任何「三」,即後代或「二」是的後代「一」使用$('.one .two .three')
,如果你想在同一只,他們是直接的孩子,你可以使用$('.one > .two > .three')
如果你碰巧已經jQuery對象爲「一個」節點可以限制你以前的搜索是這樣的: $('.three' , theOne)
,$(' .two .three' , theOne)
或$(' > .two > .three', theOne)
我希望其中的一個滿足您的需求,如果不是t如果你應該更好地澄清究竟是什麼情況。
最後一個是我正在尋找的 –
最後是'$('> .two> .three',theOne)'? – epeleg
$('。three',theOne)你能否給我演示一下我的html? –
在jQuery中有很多選擇子元素的方法。我建議瀏覽[API](http://api.jquery.com/category/traversing/tree-traversal/)會更好地利用你的和每個人的時間。 –
find()有什麼問題?你爲什麼需要另一種方式? – musefan
正確的方法是使用'find()'。期。 'children()'在樹中遍歷1級,'find()'遍歷所有級別。 IE瀏覽器。使用'find()' –