开发者

Help in jquery selectors

Hi please refer the following HTML code:

<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>

this is the html code which is being generated from admin section of my web application. I can't modify it and also can't change the structure of the above code. it is generating dynamically.

I need to wrap the text content in a html element using jquery wrap() method so that I can put some css on the text content and not on img element.

Note: The div element with id "content" is my own, I can access onl开发者_如何学JAVAy this using HTML.

Please help how to do this?

Thanks


Here is the jQuery way

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

You can Demo it here http://www.jsfiddle.net/K8WNR/


Not sure if you can do that with jQuery. But if you use raw JavaScript, you can look through the nodes and check out their nodeType, with 1 being Element and 3 being Text. So say f is your font element:

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.
    }
}


You could try this ...

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

Which will return this ...

<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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜