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

后端 未结 8 530
忘了有多久
忘了有多久 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:27

    A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

    You could change your HTML to this:

    <div id="div1" >
        <input type="text" class="edit1" />
        <input type="text" class="edit2" />
    </div>
    <div id="div2" >
        <input type="text" class="edit1" />
        <input type="text" class="edit2" />
    </div>
    

    Then, you could get the first item in div1 with a CSS selector like this:

    #div1 .edit1
    

    On in jQuery:

    $("#div1 .edit1")
    

    Or, if you want to iterate the items in one of your divs, you can do it like this:

    $("#div1 input").each(function(index) {
        // do something with one of the input objects
    });
    

    If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

    If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

    You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

    0 讨论(0)
  • 2020-12-04 20:27

    Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.

    When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.

    You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.

    0 讨论(0)
提交回复
热议问题