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>");
精彩评论