admin 管理员组文章数量: 1086019
<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...
本文标签: javascriptHow to get input of the 4th child of an element using classStack Overflow
版权声明:本文标题:javascript - How to get input of the 4th child of an element using class? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744091591a2532134.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论