selecting root element in jquery

后端 未结 9 647
粉色の甜心
粉色の甜心 2021-01-18 04:06

I need to be able to select the root element from a fragment without knowing the node types, class, id or hierachy.

相关标签:
9条回答
  • 2021-01-18 04:33

    If you've got your elements as a jQuery fragment like:

    var myElements = $('<div id="0">
    <div id="0a">
        <div id="a01"></div>
    </div>
    <div id="0b">
    </div>
    <div id="0c">
    </div>
    </div>');
    

    then you can find the first element by:

    myElements.filter(":first")
    

    The filter function looks from the root element of the fragment.

    0 讨论(0)
  • 2021-01-18 04:34

    I'm more of a Prototype guy, but I think you could get all the nodes then get the first node in the array:

    $('*')[0]
    

    Then get the child items of that (for 0a, 0b and 0c)

    $('*')[0].children()
    
    0 讨论(0)
  • 2021-01-18 04:38

    jQuery is not needed...

    var root = document.firstChild;
    
    0 讨论(0)
  • 2021-01-18 04:42

    OK, so what you need to do is the following (presuming that you are using the sample you've got), if you want to find the top level node using jquery is the following:

     $('*:not(* *)');  
    

    What you are literally asking for here is for all nodes that are not children of other nodes. The problem is that for a html document, this will always give you only the html element, which isn't particularly useful. So, if you want to find the top level element within the body of a html document, you'd use something a lot simpler:

     $('body > *');
    

    if you then wanted the second level, you'd just go

     $('body > * > *');
    

    But, presuming you have some sort of arbitrary document structure (like the foo one you mention), what you can do is use the first example to find the first level:

     $('*:not(* *)');
    

    and then for the second level

     $('*:not(* *)').find('> *');
    

    and for the third level

     $('*:not(* *)').find('> * > *');
    

    and so on and so forth. If you're looking for a root div element (presuming that your sample is like the question), you can do this:

     $('div:not(div div)');
    

    and so on, replacing * with div. Not really sure why you'd want to do this, but it will work. The problem is the question doesn't really provide enough context for us to give you a better alternative.

    0 讨论(0)
  • 2021-01-18 04:44

    If you want to select the top level parent of an element but still under the body, I'd go

    $(obj).parents().filter('body > *')
    
    0 讨论(0)
  • 2021-01-18 04:45

    I get html fragment from ajax call, and I also need to get the root div from it. What I did was simply call $(data), and jQuery will parse the returning text as HTML and give you the root.

    $.ajax path,
      type: 'GET'
      contentType: 'application/x-www-form-urlencoded;charset=UTF-8'
      success: (data) ->
        $(data)
    
    0 讨论(0)
提交回复
热议问题