开发者

How to select some particular text right after <li> with jQuery?

开发者 https://www.devze.com 2023-03-25 22:17 出处:网络
I have something like that : <ul> <li> ... </li> <li> Office <table> ....... </table>

I have something like that :

<ul>
  <li>
    ...
  </li>
  <li>
    Office
    <table>
      .......
    </table>
  </li>
</ul>

And i want to replace Office with <h3>Office</h3> so i did :

$("li:contains('Office')").replaceWith('<h3>Office</h3>');

But it's replacing me all the <li> (so it deletes the table too...) I know it's normal but how to replace just the t开发者_StackOverflow中文版ext Office please ?


Use .contents and .eq to select just the first node.

 $("li:contains('Office')").contents().eq(0).replaceWith('<h3>Office</h3>');

Example: http://jsfiddle.net/ppqvt/


You can use contents() to obtain all the direct children of your <li> element, and filter() to accumulate the text nodes that occur before the <table> element.

From there, you can use wrapAll() to create an <h3> element around the text nodes:

var $contents = $("li:contains('Office')").contents();
var tableIndex = contents.index("table");
$contents.filter(function(index) {
    return this.nodeType == 3 && index < tableIndex;
}).wrapAll("<h3>");
0

精彩评论

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