user576510
user576510

Reputation: 5915

selecting td from string

I have the following Html stirng stored in a JS variable:

<td>
  <input onclick="Clicked(this);" type="radio" name="mmBox" id="mmBox">
</td>
<td>First Cell</td>
<td>2nd TD</td>
<td>3rd TD</td>
<td>4th TD</td>
<td>5th TD</td>
<td></td>

I depending on need I need to select 2nd, 3rd and 4th <td>

I have tried the following but it do not return anything:

console.log("6 " + $(selectedRow).wrap("<tr></tr>").children("td:nth-child(2)").html());

or

console.log("6 " + $(selectedRow).find("td:eq(2)").text());

Even with .find and .select methods as well but it do not return anything.

Please help me, I want to query <td> and value inside it

Upvotes: 1

Views: 86

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115242

The wrap() method wrap each td with separate tr element, I think you need a single tr which wraps all the element for that use wrapAll() method. Although use filter() method since you need filter out td from the jQuery element and not from its children. Actually wrapping with tr is completely unnecessary if you just want to fetch the content.

var selectedRow = '<td><input onclick="Clicked(this);" type="radio" name="mmBox" id="mmBox"></td><td>First Cell</td><td>2nd TD</td><td>3rd TD</td><td>4th TD</td><td>5th TD</td><td></td>';
console.log("6 " + $(selectedRow).wrapAll("<tr></tr>").filter("td:nth-child(2)").html());
// by removing code which wraps the elements
console.log("6 " + $(selectedRow).filter("td:nth-child(2)").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Ram
Ram

Reputation: 144709

Assuming selectedRow variable contains the html string that you have posted, you should use the .filter method instead of the .find:

$(selectedRow).filter(":eq(2)").text();

Or by using the .eq method:

$(selectedRow).eq(1).text();

Note that .eq is zero-based so 1 selects the second element in the set.

Upvotes: 2

charlietfl
charlietfl

Reputation: 171690

Do it the other way around....create a row element first and set the cells in that row then you can use find on the row object

var $row = $('<tr>').html(selectedRow);
console.log("6 " + $row.find("td:eq(2)").text());

Upvotes: 2

Related Questions