2011-12-14 3 views
1

自分のニーズに合ったセレクターが見つかりません。.infospanの要素がimgの要素の前にあります。img要素の前にある最初のスパン(その間の任意のdom要素)を選択しますか?

<div> <!-- common parent --> 
    <span class="info"></span> 
    <p>Stuff</p><span>Other sfuff</span> 
    <!-- p, span or possibly other dom element before img --> 
    <img src="" alt="" class="highlight" /> 

    <span class="info"></span> 
    <!-- here nothing precede img element --> 
    <img src="" alt="" class="highlight" /> 
</div> 

私が試した:

$("img.highlight").prev("span.info")を秒1での作品ながら(つまり直前の兄弟です)最初の例では失敗します私はjQueryのに新たなんだ、我慢してください。

$("img.highlight").prevAll("span.info")は、最初のスパンも選択されるため、2番目のスパンで失敗します。

EDIT

$("img.highlight").each(function() { 
    $info = $(this).selector("span.info") // selector() to be replaced 
    $info.text($(this).attr("src")); // Fill the right span.info 
}); 
+0

を行うことができ、私は混乱しています。あなたはcommon-parent 'div'の最初の' span.info'だけを望みますか? –

+0

@lburk nope、申し訳ありませんが、英語は母国語ではありません。私は各imgの最初の先行するspan.infoが欲しい。 – gremo

答えて

1

$('img.highlight').prevUntil('img.highlight', 'span.info')

+0

パーフェクト、ここにポイントがあります。ありがとう。 – gremo

1

次が動作しているようです:

$('img').each(
    function(){ 
     $(this).prevAll('span.info'); 
    }); 

JS Fiddle demoこれは実際のコードでよりきれいにします。

デモでは、情報spanにコンテンツを追加し、影響を受けたものを明確にするためにCSSを調整しました。しかし、同じテクニックは、あなたのニーズに対応する必要があります。

+0

助けてくれてありがとう、おそらく質問は100%きれいではない、私の編集を参照してください。 – gremo

1

あなたは

$("img.highlight").prevAll("span.info:first")