If I have a list of table rows stored in a variable, is there a way of placing only one of those rows (with a specific ID) in to anoter variable?
For example, if tableRows was this –
<tr id="0"></tr>
<tr id="1"></tr>
<tr id="2"></tr>
<tr id="3"></tr>
<tr id="4"></tr>
How could I set singleRow to <tr id="2"></tr>?
Assuming
tableRowscontains a string of HTML:If it’s already a jQuery object wrapping the HTML string then you can omit the call to jQuery:
The
filtermethod reduces the matched set of elements to those matching the selector (or passing a test defined by a function).Here’s a working example.
However, it may be worth noting that the resulting
singleRowvariable will contain an instance of jQuery, not a string literal liketableRowscontains. To extract a string out of that you need a little bit of trickery:Basically, you append the desired element to a new one (in this case it’s a
div) and then callhtmlon that. As thehtmlmethod returns a string, you have a string containing the contents of the new element, which is your desired element.