jqueryjquery-traversing

jQuery parse string to get first <td> tag?


I have the following string:

<td class="internal-first-row add-internal-hover cursor">Fname Lname</td>
<td class="center add-internal-hover cursor">Campaign Manager</td>
<td class="center classval add-internal-hover cursor">
    <input id="h_user_id_147" value="147" type="hidden">
    <a id="delete-internal-user-btn" href="javascript:void(0);">X</a>
</td>

In jQuery, how can I get the html() only of the 1st <td> tag which is "Fname Lname"?


Solution

  • Use the below code

    var value = $('td:first').html()
    console.log(value)
    

    to be more precise and for performance reasons, find within your table

    var value = $('#table_id').find('td:first').html();
    
    or 
    
    var value = $('#table_id').find('td').first().html();
    

    btw.. your td elements should be within tr elements :) to make it as correct html markup.

    If that is a plain string, you can get the value using

    var value = $('<table>')append(
                    '<tr>'+your_html_string+'</tr>'
                ).find('td:first').html();