Jquery remove closest tr fail
I want to do the manipulation to remove the closest table when certain wording is exist at html.
I cannot assume the span class will exist there, because the html is retrieved from other side, they may change it by adding, removing any class anytime.
It need to be do开发者_StackOverflow社区ne on page load, not when the class/id event inside is clicked.
Kinda challenging. Any idea how to achieve this?
On page load,
jquery to detect whether "Hello how are you" is exist in page.
If exist
remove the whole td or tr or table for this particular.
else
do nothing.
end
Code as below:
function replaceText()
{
var debug;
debug= "";
$("*").each(function() {
if($(this).children().length==0)
{
// $(this).text($(this).text().replace('Hello how are you', 'yohoo'));
debug= debug + $(this).val() + "<br>";
if($(this).val()=="Hello how are you")
{
$(this).closest('table').remove();
}
}
});
//alert(debug);
}
<div>
<table>
<tr>
<td colspan="2">
<div>
<table>
<tr>
<td ><span class="myclass">Hello how are you</span></td>
<td><a href="testing.php"></a></td>
</tr>
</table>
</div>
</td>
</tr>
<tr colspan="2">
<table>
<tr>
<td><b>want to remove this</b></td>
</tr>
</table>
</tr>
<tr>
<td>other content 1</td>
<td>other content 2</td>
</tr>
</table>
</div>
You can use :contains
to check if text exists:
$(":contains('Hello how are you')").each(function(n){
if ($(this).children().length == 0){
$(this).closest('table').remove();
}
});
This code will loop through all elements that contain the text 'Hello how are you'. If you want an exact match you can also check $(this).text() == 'Hello how are you'
. Once it finds these elements it checks that they don't have any children and then removes the closest table if they pass that condition.
To run this code when the page loads, wrap it in a document.ready
function:
$(document).ready(function(){
...
});
精彩评论