2016-03-21 47 views
-2

我有以下結構。使用jquery從子節點的目標父節點

<dl> 
    <dt class="tab">..</dt> 
    <dd class="tab-container">..</dd> 
    <dt class="tab"> 
     <div class="hi">hello</div> 
    </dt> 
    <dd class="tab-container">...</dd> 
    <dt class="tab">...</dt> 
    <dd class="tab-container">...</dd> 
</dl> 

我想添加新的類到最後dd元素點擊「嗨」div .how我可以實現使用jQuery。

+0

你到目前爲止試過了哪些代碼? – shamsup

+0

stackoverflow是用於解決**現有的**代碼和沒有* giv-me-the-codez *網站的問題。 – cramopy

回答

1

嘗試學習遍歷。回答你的問題[在評論中提問]

$(this).parents('dl').prev().closest('ul').children('li').eq(-2).addClass('new classs'); 
3

可以爲closest()用它來獲得相關dd祖先然後瞄準最後dl

$('div.hi').on('click', function(){ 
    $(this).closest('dl').children('dd:last-child').addClass('myNewClass'); 
}); 
+0

如何瞄準第二個最後的dd? – user5962477

+0

@ user5962477使用具有負數索引的'eq()':'$(this).closest('dl')。children('dd')。eq(-2)' –

+0

thanks.one more questions .how can i target其他不屬於

標籤的元素。 – user5962477

1

這聽起來像你想是這樣的:

$(".hi").click(function() { 
    $(this).closest("dl").find("dd:last-child").addClass("blue"); 
}); 

例子:https://jsfiddle.net/z24toqL2/

0

一種方法是使用jQuery.parents遍歷DOM樹,直到找到dl元素。

$('.hi').on('click', function() { 
    $(this).parents('dl').find('dd:last').addClass('my-new-class'); 
}); 

這裏是jQuery的API documentation category對DOM樹的遍歷 - 不止一種方法去做一件事。

1

你好:)你可以使用父母()或父母() - documentation for parents()

所以,試試這個:

$('.hi').on('click', function() { 
    // In that case- parents('dl') - try to catch a dl parent 
    $(this).parents('dl').find('dd:last-of-type').addClass('new-class'); 
}); 

你可以view online here in jsfiddle

相關問題