Reputation: 121
So example I have this kind of table
<table>
<tr>
<td><input textbox text="test1"> <!-- FIND only this element -->
<div></div>
</td>
<td>test2 <!-- FIND only this text and disregard checkbox input-->
<checkbox>
</td>
</tr>
</table>
I am making a .each()
function which would only get the values of every first element of every td
per row.
I have tried
$(this).find('tr td:first-child').each()
function but I know that this would only get the first td
of every row and it would not go through every td
which is I want.
Upvotes: 1
Views: 4137
Reputation: 104
$('table tr td').each(function() {
//First child of td
$(this).children(':first').css('border-color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input textbox text="test1" value="name"> <!-- FIND only this element -->
<div></div>
</td>
<td>test2 <input type="checkbox">
</td>
</tr>
<tr>
<td><input textbox text="test1">
<div></div>
</td>
<td>test2
<input type="checkbox">
</td>
</tr>
<tr>
<td><input textbox text="test1">
<div></div>
</td>
<td>test2 <input type="checkbox">
</td>
</tr>
<tr>
<td><input textbox text="test1" value="name">
<div></div>
</td>
<td>test2 <input type="checkbox">
</td>
</tr>
</table>
Hope so this will helpful for you
Upvotes: 0
Reputation: 6996
<table border="1" class="myTable">
<tr>
<td>
<span>First</span>
<span>Second</span>
<span>Third</span>
</td>
<td>
<span>First</span>
<span>Second</span>
<span>Third</span>
</td>
</tr>
</table>
//jQuery code
$('.myTable tr td').each(function() {
//First child of td
$(this).children(':first').css('color', 'red');
});
Here is the working sample
If you just need the text of the first element then you can do so by using the text() function
$('.myTable tr td').each(function() {
//First child of td
var firstChild = $(this).children(':first');
alert(firstChild.text());
});
Upvotes: 4
Reputation: 11975
In your case, you want the first value of anything inside td
tag including text node so you can try to use childNodes or .contents():
Example:
$('table tr td').each(function() {
console.log($(this).contents()[0]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input textbox text="test1"> <!-- FIND only this element -->
<div></div>
</td>
<td>test2 <!-- FIND only this text and disregard checkbox input-->
<checkbox></checkbox>
</td>
</tr>
</table>
Or without jquery:
document.querySelectorAll('table tr td').forEach(function(td) {
console.log(td.childNodes[0]);
});
<table>
<tr>
<td><input textbox text="test1"> <!-- FIND only this element -->
<div></div>
</td>
<td>test2 <!-- FIND only this text and disregard checkbox input-->
<checkbox></checkbox>
</td>
</tr>
</table>
Upvotes: 0