I have 4 columns and about 10 rows in a table. I’m trying to have an onclick
event that searches through the row that was clicked and removes "T" from that row but right now it’s searching and removing all the "T" from the table, not just the row clicked. What should I change?
$('#table_output tbody').on('click', 'tr', function() {
console.log(table.row(this).data());
$(':contains("T")').each(function(){
$(this).html($this).html().split("T").join(""));
});
alert(JSON.stringify(table.row(this).data()));
})
2
Answers
:contains("T")
will find every element that contains ‘T’. I replaced that with$(this).find(':contains("T")')
, which searches only within the children of the<tr>
that was clicked.You also had a few typos that I fixed, as well as some unknown variables like
table
, which I’ve commented out.Here is another take on the script. I chose to operate solely on actual text nodes (
this.nodeType===Node.TEXT_NODE
). This will reliably avoid messing up html markup in the process. In my example I replace all lowercase "t" with empty strings (""). Applying a.replaceAll("t","")
directly on the innerHTML string of an element containing "t" would mess up the inner table table structure in my second row. By limiting the action on text nodes only everything still stays intact:Just out of interest I looked for a way to find text nodes of an element without using jQuery. And there is such a way:
I got this – in a slightly longer form – from Chris West’s Blog.