2012-04-02 17 views
0

JavascriptとjQueryを使用して、HTMLファイルからテキストを含むノードを取得しようとしています。 私は `htmlファイルからテキストを抽出する

<div>txt0 
<span>txt1</span> 
txt2 
</div> 

How can I select elements that meets this criteria?? Meaning, I need to retrieve theのdiv and the span`のようなノードを持っている、そしてテキストの位置を知るためにも、良いだろう場合。

私はテキストを後の機能で画像に置き換えることを試みています。 が、私はこの

`

$('*').each(function(indx, elm){ 
    var txt = $(elm).text(); 
    // my code to replace text with images here 
}); 

`

を試みたが、それは必要な結果を得ることはありません...それは最初の要素内のすべての構文解析を行い、そして完全にHTMLを変更します。

+0

を使用して次にこの

<div> <span>txt0</span> <span>txt1</span> <span>txt2</span> </div> 

のようなものに変更することを検討してください、あなたはそれらのテキストを持っているすべての要素を選択するには欠けていますか? – Lix

+0

'

txt0txt1txt2
'はあなたがそれを操作した後何に変わるのですか? –

+0

@lixはい、 @ JuanMendes:見つけたときに変更します – zeacuss

答えて

1

私はあなたが解決しようとしていることを正確にはわかりませんが、あなたのセレクタではさらに具体的かもしれません。あなたのhtmlにIDおよび/またはクラスを追加することにより

$("div span").text(); // returns 'txt1' 
$("div").text();  // returns 'txt0txt1txt2' 

、あなたは非常に特異的であることができる:

<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div> 

...

// returns all spans with class 
// "middlename" inside divs with class "name" 
$("div.name span.middlename").text(); 

// returns the first span with class 
// "middlename" inside the fourth div 
// with class "name" 
$("div.name[3] span.middlename[0]").text(); 

jQueryのこれらのセレクタのかなりgood documentationを持っています。

これで解決しない場合は、解決しようとしている問題の説明を検討してください。

0

あなたのマークアップ構造は少し不安です。 jQueryの

$("div span").each(function(k,v) { 
    $(this).html("<img src=\""+v+".jpg\" />"); //replace with the image 
});