Search code examples
jquerytooltip

Add part of code to a td in jquery


I have a little problem with adding some HTML code using jQuery into a td element in an existing table. My HTML code is:

<table>
    <tbody>
        <tr>
            <td>Something</td>
            <td><strong>10</strong></td>
        </tr>
    </table>
</tbody>

Now I have written this jQuery code to add a tooltip in the cell containing 'Something':

$('table tr').each(function(){
    if ($(this).find('td').text() == 'Something') {
        $(this).html('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>')
    }
});

In this case the jQuery function works correctly, I have added a tooltip to my td content, but the second td element is removed. I have tried using .find('td:first') but in any case the second td disappears.

Can someone tell me how to write my jQuery code correctly so that the second td stays in the page? Thank you so much for help.


Solution

  • The issue is because you're overwriting all the HTML within the tr element, not just replacing the first td containing the Something text value. Try this instead:

    $('table td').each(function(){
        if ($(this).text() == 'Something'){
            $(this).replaceWith('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>');
        }
    });