How to get a DOM Element from a JQuery Selector

前端 未结 4 888
不思量自难忘°
不思量自难忘° 2020-11-22 13:26

I\'m having an impossibly hard time finding out to get the actual DOMElement from a jquery selector. Sample Code:



        
相关标签:
4条回答
  • 2020-11-22 13:30

    I needed to get the element as a string.

    jQuery("#bob").get(0).outerHTML;
    

    Which will give you something like:

    <input type="text" id="bob" value="hello world" />
    

    ...as a string rather than a DOM element.

    0 讨论(0)
  • 2020-11-22 13:31

    If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

    But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

    UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en@googlegroups.com/msg04461.html

    $(this).attr("checked") ? $(this).val() : 0
    

    This will return the value if it's checked, or 0 if it's not.

    $(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

    0 讨论(0)
  • 2020-11-22 13:40

    Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:

    $('#element').get(0);
    

    I have verified this actually returns the DOM element that was matched.

    0 讨论(0)
  • 2020-11-22 13:41

    You can access the raw DOM element with:

    $("table").get(0);
    

    or more simply:

    $("table")[0];
    

    There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

    $(":checkbox").click(function() {
      if ($(this).is(":checked")) {
        // do stuff
      }
    });
    

    is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

    $(":checkbox").each(function(i, elem) {
      $(elem).data("index", i);
    });
    $(":checkbox").click(function() {
      if ($(this).is(":checked") && $(this).data("index") == 0) {
        // do stuff
      }
    });
    

    Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

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