2010-11-03 77 views
0

你好請參考下面的HTML代碼:幫助在jQuery選擇

<div id="content"> 
    <p> 
     <font size='2'> 
     <img src="something.jpg" width="500" height="500" /> 
     this is the text content. this is the text content. this is the text content... 
     </font> 
    </p> 
</div> 

這是正在從我的web應用程序的管理部分生成的HTML代碼。我無法修改它,也無法更改上述代碼的結構。它是動態生成的。

我需要使用jquery wrap()方法將文本內容包裝在html元素中,以便我可以將一些CSS放在文本內容上而不是img元素上。

注意:id爲「content」的div元素是我自己的,我只能使用HTML訪問它。

請幫忙怎麼做?

感謝

+0

我試着用這個var elm = $(「#content p font」)。children(「:not(img)」)。wrap(「

」); – Bhupi 2010-11-03 04:02:53

回答

6

這裏是jQuery的方式

$("p > font") 
    .contents() 
    .filter(function() { 
    return this.nodeType == 3; 
    }).wrap('<span style="color:#FF0000" />'); 

You can Demo it herehttp://www.jsfiddle.net/K8WNR/

+0

@Bhupi ...沒問題 – 2010-11-03 04:21:29

+1

不錯,我投票贊成,因爲它比我的回答要好。 – jpsimons 2010-11-04 00:06:22

3

不知道,如果你能做到這一點與jQuery。但是,如果您使用原始JavaScript,則可以查看節點並查看它們的nodeType,其中1是Element,3是Text。所以說f是你的字體元素:

for (var i=0; i < f.childNodes.length; i++) { 
    if (f.childNodes[i].nodeType == 3) { 
     var text = f.nodeValue; 
     // Remove the text node, insert a new span node and plug in the text. 
    } 
} 
0

你可以試試這個...

$(function() { 
    $("#content").find("p > font").each(function() { 
    var $this = $(this).wrapInner(document.createElement("div")); 
    var $img = $this.find('img').remove(); 
    $this.prepend($img); 
    }) 
}); 

將返回這...

<p> 
    <img height="500" width="500" src="something.jpg"> 
    <div> 
     this is the text content. this is the text content. this is the text content... 
    </div> 
</p> 
+0

謝謝,但我只想包裝「文字內容」而不是img元素。 – Bhupi 2010-11-03 04:35:42

+0

好的,我修改了上面的代碼。約翰的樣品會產生一些額外的空標籤,但仍然有效。 - 祝你好運 – rsturim 2010-11-03 05:06:46