jQuery - selecting elements from inside a element

前端 未结 7 1562
广开言路
广开言路 2020-12-02 08:19

let\'s say I have a markup like this:

... ... ...

and

相关标签:
7条回答
  • 2020-12-02 08:38

    You can use find option to select an element inside another. For example, to find an element with id txtName in a particular div, you can use like

    var name = $('#div1').find('#txtName').val();
    
    0 讨论(0)
  • 2020-12-02 08:49

    ....but $('span', $('#foo')); doesn't work?

    This method is called as providing selector context.

    In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

    eg.

    $("span",".cont1").css("background", '#F00');
    

    The above line will select all spans within the container having the class named cont1.

    DEMO

    0 讨论(0)
  • 2020-12-02 08:51

    Have a look here -- to query a sub-element of an element:

    $(document.getElementById('parentid')).find('div#' + divID + ' span.child');

    0 讨论(0)
  • 2020-12-02 08:52

    Why not just use:

    $("#foo span")
    

    or

    $("#foo > span")
    

    $('span', $('#foo')); works fine on my machine ;)

    0 讨论(0)
  • 2020-12-02 08:57

    both seem to be working.

    see fiddle: http://jsfiddle.net/maniator/PSxkS/

    0 讨论(0)
  • 2020-12-02 09:00

    You can use any one these [starting from the fastest]

    $("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")
    

    Take a look

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