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

html - JavaScript: Get next element from Parent - Stack Overflow

programmeradmin3浏览0评论

I want to disable the next element of the parent of a tag:
HTML:

<span>     
    <input type="checkbox" onchange="disableInput(this)">     
</span>
<input type="text" />
<!-- When checkbox changed, disable inputfield -->

Javascript:

<script>
    function disableInput(element){
        element.parentNode.nextSibling.disabled = true;
    }
</script>

This didn't work. Can someone help me?

I want to disable the next element of the parent of a tag:
HTML:

<span>     
    <input type="checkbox" onchange="disableInput(this)">     
</span>
<input type="text" />
<!-- When checkbox changed, disable inputfield -->

Javascript:

<script>
    function disableInput(element){
        element.parentNode.nextSibling.disabled = true;
    }
</script>

This didn't work. Can someone help me?

Share Improve this question edited Feb 1, 2015 at 22:08 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked Apr 28, 2014 at 18:57 ThomThom 6215 gold badges14 silver badges30 bronze badges 4
  • You'll find the nextSibling is a text node. Remove the white-space between </span> and <input.. and you'll see results. jsfiddle/LaTsd – George Commented Apr 28, 2014 at 19:00
  • 1 Remove the white space between the closing span and input and it works. – j08691 Commented Apr 28, 2014 at 19:00
  • There is no error, I didn't work – Thom Commented Apr 28, 2014 at 19:00
  • @j08691 It Works! But how can I fix this, because in my code is it proper to indent and break lines – Thom Commented Apr 28, 2014 at 19:03
Add a ment  | 

2 Answers 2

Reset to default 5

Try this. nextSibling includes text nodes (including empty space), but nextElementSibling doesn't.

function disableInput(element) {
  element.parentNode.nextElementSibling.disabled = true;
}

You can use nextElementSibling

  function disableInput(element){
        element.parentNode.nextElementSibling.disabled = true;
  }

It will select actual DOM element. The drawback - this may not be patible with older browsers like IE8.

发布评论

评论列表(0)

  1. 暂无评论