Simple way to get element by id within a div tag?

后端 未结 8 605
忘了有多久
忘了有多久 2020-12-04 19:44

Please forgive me if I repeat the question.

I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is

8条回答
  •  情话喂你
    2020-12-04 20:20

    You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.

    You should be using a class, or just iterating through the inputs and keeping track of an index.

    Try something like this:

    var div2 = document.getElementById('div2');
    for(i = j = 0; i < div2.childNodes.length; i++)
        if(div2.childNodes[i].nodeName == 'INPUT'){
            j++;
            var input = div2.childNodes[i];
            alert('This is edit'+j+': '+input);
        }
    

    JSFiddle

提交回复
热议问题