How to get a html element by name

前端 未结 3 1984
盖世英雄少女心
盖世英雄少女心 2021-01-18 20:33

Is there a way in java script to get only a particular name instead of using document.getElementsByName(\"x\"); which return an array? I have a kind of special

相关标签:
3条回答
  • 2021-01-18 21:02

    Just get the first element:

    document.getElementsByName("x")[0];
    

    Or for safety:

    function getFirstElementByName(element_name) {
        var elements = document.getElementsByName(element_name);
        if (elements.length) {
            return elements[0];
        } else {
            return undefined;
        }
    }
    

    (BTW getElementsByName returns a collection, not an array.)

    0 讨论(0)
  • 2021-01-18 21:13

    If you're looking for a single element, take the first one from the nodelist, for example:

    var element = document.getElementsByName("x")[0];
    

    You can test it out here.

    0 讨论(0)
  • 2021-01-18 21:17

    Or use jQuery, so you don't have to bother with all the browser annoyance.

    You just have to do this:

    $("*[name='x']").first();
    

    To get the first element with that name. If you know the element type than you can use it instead of "*". jQuery will make your life easier every time!

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