3

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.

1
  • 1
    Please post some code which you have tried so far. So others can point you in right direction Commented Aug 19, 2016 at 11:12

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, it works fine now, thanks a lot! I thought that parseHTML returns an array of jQuery elements and not a regular Javascript array.
@EliasGarciaMariño: :-) Well, even if it did, label.first() would fail because regardless of what it contains (DOM elements vs. jQuery objects), the array label referred to won't have a first method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.