Why use jQuery(selector).get(0) instead of jQuery(selector)[0] to get DOM element?

前端 未结 4 1501
臣服心动
臣服心动 2021-02-19 02:34

Using jQuery is there any benefit to using $(selector).get(0) over $(selector)[0] if I just want to get the first item in the jQuery array as a DOM ele

4条回答
  •  抹茶落季
    2021-02-19 03:02

    As an ardent fan of code readability by humans I suggest neither approach is satisfying. .get(0) and [0] look too much like container indexing. More is at stake when converting a jQuery object to a DOM object. So I introduce a function to name what's going on.

    function dom_from_$($jquery_object) {
        var dom_object = $jquery_object.get(0);
        return dom_object;
    }
    

    Used like this:

    var domElement = dom_from_$($(selector));
    

提交回复
热议问题