最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get input of the 4th child of an element using class? - Stack Overflow

programmeradmin7浏览0评论
<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 0
Add a ment  | 

5 Answers 5

Reset to default 4

Use nth:child selector.

The selector matches a number of child elements whose numeric 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...

发布评论

评论列表(0)

  1. 暂无评论