javascript - How to use nextElementSibling to find the next node in js
天蓬老师
天蓬老师 2017-05-19 10:12:12
0
3
678
<script type="text/javascript">
    function getElements(){
    var x=document.getElementById("dialogArea");
    x.nextElementSibling.nextElementSibling.value="30";//该方法错误
    }
</script>

<input type="hidden" name="dinwei" class="dinwei" id="dialogArea" value="" />
<input name="myInput" type="text" size="20" value="How1 many input elements?"/>
<input name="myInput" type="text" size="20" value="How2 many input elements?"/>
<input name="myInput" type="text" size="20" value="How3 many input elements?"/>
<input type="button"  onclick="getElements()"value="button" />

1. Use nextElementSibling to find the next node with the id of dialogArea and modify its value.
2. Only use native js without jquery.
3. The purpose is to use the hidden input as the positioning coordinate to find the specified input downwards when the ID and class of the input cannot be obtained under some special circumstances.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
迷茫

Can I get dom by placing script in front of dom...

I read the question wrong, but it seems there is nothing wrong with it. Can you post a screenshot of the error? Furthermore, it is best to add an existential judgment to such a continuous judgment, otherwise problems may easily arise. Similar to:

if (dom.next) {
    dom.next.next
}
给我你的怀抱

var test1 = document.getElementById('dialogArea');
var test2= test.nextElementSibling.nextElementSibling;

淡淡烟草味

Then your html cannot be line-wrapped. If it is line-wrapped, there will be a nextSibling of text type behind each input. The blank character is also equivalent to a text node

var x=document.getElementById("dialogArea");
x.nextElementSibling.nextElementSibling.value = "30";
<input type="hidden" name="dinwei" class="dinwei" id="dialogArea" value="" /><input name="myInput" type="text" size="20" value="How1 many input elements?"/><input name="myInput" type="text" size="20" value="How2 many input elements?"/><input name="myInput" type="text" size="20" value="How3 many input elements?"/><input type="button"  onclick="getElements()"value="button" />

It’s best to use jquery. If you have to use js, you can write it like this.

var x=document.getElementById("dialogArea");
next(next(x)).value="30";

function next(e){
        e = e.nextSibling;
        if(e.nodeType == 3){ // 3是指text类型
            e = e.nextSibling;
        }
        return e;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template