Reputation: 1091
I am trying to access the data in a table row. The data may be in a <td>
tag, or as text in an input, or as a checkbox in an input, or a button.
As a demonstration I have a small table:-
<table border="1">
<tr>
<td dir="ltr" id="test1" class="tLine" nowrap>Column One</td>
<td><input type="checkbox" name="vehicle" value="Car" checked>Check Box.</td>
<td>
<button type="button" class="clicked">Update</button>
</td>
</tr>
</table>
The Javascript is :-
<script>
$(".clicked").click(function() {
var $row = $(this).closest("tr"); // Finds the closest row <tr>
var $tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
console.log($tds[0].tagName); // 'TD'
console.log($tds[1].tagName); // 'TD'
$.each($tds, function(index, value) { // Visits every single <td> element
console.log($tds[index].tagName); // 'TD'
console.log($(this).tagName); // Undefined
console.log($(each).tagName); // Fails
});
});
</script>
What exactly is the each in the 2nd loop and how do I use it? Why is the $(this).tagName undefined?
Once I get the TD element I can check what the content is by looking at children...
I am also looking at javascript/jquery table options like SlickGred, jsgrid and DataTables, but would like to understand the code above first.
Upvotes: 1
Views: 113
Reputation: 735
What exactly is the each in the 2nd loop and how do I use it?
If you mean the one element in the collection it is value
, the second parameter in your callback function. But with $.each
you can also do this with this
.
Why is the $(this).tagName undefined?
Because $(this)
instantiates a jQuery object, and there is no tagName
property in a jQuery object. You could do this.tagName
, or value.tagName
.
The reason why $tds[0].tagName
works is that although $tds
is a jQuery object, it is also an "array-like" object because all the individual element that are wrapped in it are placed in properties/indices like '0'
, '1'
etc. So when you do $tds[0]
, you get the actual element and it has the tagName
property.
Upvotes: 2