JQuery methods and DOM properties

后端 未结 4 853
梦如初夏
梦如初夏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题