Elias Garcia Mariño Elias Garcia Mariño - 3 months ago 6
jQuery Question

jQuery parse HTML element and get it's inner HTML

I have a table in HTML with table rows, but some elements have an

<span>
elements inside, so i want to get the inner html of that span.

I have an array with all
<tr>
elements (not jQuery Objects, because I get it from the DataTables plugin API), so I have this code:

if (data[i+1].includes("span")) {
var label = $.parseHTML(data[i+1]);
// editFormInputs.eq(i).val(label.first().html());
} else {
editFormInputs.eq(i).val(data[i+1]);
}


So the problem is on the commented line. I tried to convert the html to jQuery element with
parseHTML()
, which returns an array. This works fine, but when I try to get the first element of the array with the
first()
function it gives me an error
first() is not a function
, so what I am doing wrong? Thanks.

Answer

parseHTML is one of the rare jQuery functions that doesn't give you a jQuery object; it gives you an array:

jQuery.parseHTML( data [, context ] [, keepScripts ] )

Returns: Array

Description: Parses a string into an array of DOM nodes.

(my emphasis)

So:

editFormInputs.eq(i).val($(label[0]).html());

Note that label[0] will be the tr element. It wasn't clear to me that you wanted the HTML of the tr element vs. one of its spans, but in any case, that's the reason for the error.

If you want the HTML of (say) the first span in the tr:

editFormInputs.eq(i).val($(label[0]).find("span").first().html());
Comments