2016-09-28 22 views
0
<div> 
    <input type="text"> 
    <span id="ending_point"> 
    <label> 
     <span> 
     <input type="text" id="starting_point"> 
      <span> 
      </span> 
     </span> 
    </label> 
    </span> 
</div> 

ここで、前の兄弟が "入力"である要素の祖先(ここではid:starting_point)を探したいと思います。前の兄弟が "input"なので答えはid "ending_point"でスパンです。これを見つけるには? $("input + span"):これはあなたのセレクタが兄弟がjqueryの特定の要素である要素の最初の祖先を見つける方法

$("input + span").first(); 

です:

答えて

0

です事前に、

を使用します
$("#starting_point").parent().parent().parent().parent().find("#ending_point"); 

または.parentsUntil()(https://api.jquery.com/parentsUntil/)で何かを実行します。

階層がわからない場合(動的に作成された)、#starting_pointが#ending_pointよりも「低い」場合は作成することができますあなたが探している型のすべてのレベルをチェックするための再帰的な関数です。関数で使用

// start_obj is the jQuery object you start your recursive function from 
// end_type is the type of element you are looking for in the hierarchy (e.g. input[ type="text" ] in your case 

function get_sibling_on_other_level(start_obj, end_type) { 
    var grampy = start_obj.parent().parent(); 
    if (grampy.find(end_type).length > 0) { 
     return grampy.children(end_type); 
    } else { 
     // start the iteration "one level higher" 
     // actually you should stop at "body" level - if you did not find 
     // what you were looking for, then it's not in that branch of hierarchy 
     get_sibling_on_other_level(start_obj.parent(), end_type); 
    } 
} 

他のjQueryの方法:https://api.jquery.com/children/

+0

これは、私はあなたをwant.Thank正確である:) – AmudhaVigneshwaran

0

は、ここに私のソリューションです。それは、入力の後に瞬時に続くすべてのスパンを選択します。 .first()を使用すると、最初のものを選択します。

あなたのためにJSFiddleを作成しました。あなたは正確に階層を知っている場合

var $ep = $("#starting_point") 
 
    .parents() 
 
    .filter(function() { 
 
    return $(this).prev().is("input"); 
 
    }) 
 
    .first(); 
 

 
// NB: the parents() method return all parents, CLOSEST ONE FIRST 
 

 
console.log($ep);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<div> 
 
    <input type="text"> 
 
    <span id="ending_point"> 
 
    <label> 
 
     <span> 
 
     <input type="text" id="starting_point"> 
 
     <span></span> 
 
     </span> 
 
    </label> 
 
    </span> 
 
</div>

0

:ここ

そして、あなたは.parents.filterの組み合わせを使用することができますSelectors Reference

Greetz Eldo.ob

関連する問題