JQuery methods and DOM properties

后端 未结 4 848
梦如初夏
梦如初夏 2021-01-31 12:06

I am confused as to when I can use the DOM properties and when I could use the Jquery methods on a Jquery object. Say, I use a selector

var $elemSel = $(\'#myDi         


        
相关标签:
4条回答
  • 2021-01-31 12:30

    There is also a shortcut for get(index) function:

    $(selector)[0].nodeName
    

    Soruce: http://docs.jquery.com/Core/get#index

    0 讨论(0)
  • 2021-01-31 12:35

    Because there can be more than one match in jQuery selectors you need to get the elements out of the "array".

    You can use the get method to return a single DOM element or an array or DOM elements.

    eg:

    var elims = $("div").get();
    for(var i in elims)
        alert(elims[i].nodeName);
    

    Edit:

    $elemSel.get(0).is(':checked') will not work because you are getting the Dom object and then trying to use jQuery functions on it. If you want to get a single jQuery element use eq.

    $elemSel.eq(0).is(':checked');
    
    0 讨论(0)
  • 2021-01-31 12:38

    In order to call native DOM method you can use get(index). Or if you want to use jQuery Object method, you should wrap a native DOM element with jQuery, which will convert the DOM element into a jQuery Object, so all the methods will be available. http://www.linxinshan.com/?p=339

    0 讨论(0)
  • 2021-01-31 12:49

    You'll need to .get(0) the result to get the DOM-ready object.

    var myBox = $("div#myBox");
    alert(myBox.get(0).id); // "myBox"
    

    Read "Peeling Away the jQuery Wrapper and Finding an Array" by Cody Lindley


    Re: Edit: .is() is not a native javascript method. When you run .get(0), you are no longer working off of the jQuery object, therefore you cannot expect to run jQuery methods from it.

    If you want to run .is() on a specific result, use the :eq(index) selector, or the .eq(index) method:

    $("div:eq(1)").is(":checked"); // gets second div
    $("div").eq(1).is(":checked"); // gets second div
    

    Re: Edit # 2

    Bob, you really should create new questions, rather than asking more and more here.

    Converting a dom element to jquery object is done by passing it in a selector:

    var myBox = document.createElement("div");
    var myBoxJQ = $(myBox);
    

    Assinging This to a variable. Depends on when you do it. If by "this" you're referring to a jQuery object, then this will be a jQuery object. You can convert it by following this with .get(0).

    When this is referring to a jQuery object, you don't need to wrap it in the $(). This is redundant.

    And lastly, $elemSel.children('td').nodeName can be done like this: $elemSel.children('td')[0].nodeName or $elemSel.children('td').get(0).nodeName, where the 0 is the index of which item to access.

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