Help in jquery selectors

2019-09-06 08:13发布

问题:

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 only this using HTML.

Please help how to do this?

Thanks

回答1:

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/



回答2:

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


回答3:

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>