<tr class='abc'>
<td></td>
<td></td>
<td></td>
<td>
<input></input>
</td>
<td></td>
</tr>
I want to when i click input of the 4th child of tr , alert something, what can i do?
<tr class='abc'>
<td></td>
<td></td>
<td></td>
<td>
<input></input>
</td>
<td></td>
</tr>
I want to when i click input of the 4th child of tr , alert something, what can i do?
Share Improve this question edited Jun 27, 2016 at 6:45 sfblap asked Jun 27, 2016 at 3:33 sfblapsfblap 1712 silver badges8 bronze badges 05 Answers
Reset to default 4Use nth:child
selector.
The selector matches a number of
child elements
whosenumeric position
in the series of children matches the pattern an+b.
.abc td:nth-child(4) input
=> Selects a input
element from 4th td child
of parent .abc
element.
var elems = document.querySelectorAll('.abc td:nth-child(4) input');
[].forEach.call(elems, function(elem) { //To iterate selected elements!
elem.addEventListener('click', function() {
console.log('Clicked');
});
});
<table>
<tr class='abc'>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>
<input>And some text(Not clickable)
</td>
<td>Five</td>
</tr>
<tr class='abc'>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>
<input>And some text(Not clickable)
</td>
<td>Five</td>
</tr>
</table>
Note: As mentioned in ments, consider Browser patibility
I prefer use JQuery.
$("tr.abc").on("click", "td:eq(3) input", function(){
console.log("click the fourth td")
})
$( "tr li:nth-child(4)" )
would be the answer for more help please go tot the documentation of jquery.
https://api.jquery./nth-child-selector/
hope this answer your question.
If you can use jQuery, you can try using the nth-child()
selector.
Syntax:
$('.className element:nth-child(x)').whatever()...
Your case:
$('tr.abc td:nth-child(4)').whatever()...
I assume your class has only one, so i call with 0 index.And you want 4th child so call with index 3 js array standard ,then your input
has only one as index 0.
var g = document.getElementsByClassName("abc")[0];
g.children[3].children[0].onclick = function(){
alert('clicked');
}
If your element are more than one ,you can iterate with for loop...