jQuery - selecting elements from inside a element

2020-01-29 03:41发布

let's say I have a markup like this:

<div id="foo">
  ...
  <span id="moo">
    ...
  </span>
  ...
</div>

and I want to select #moo.

why $('#foo').find('span') works, but $('span', $('#foo')); doesn't ?

7条回答
SAY GOODBYE
2楼-- · 2020-01-29 04:00

Why not just use:

$("#foo span")

or

$("#foo > span")

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

查看更多
淡お忘
3楼-- · 2020-01-29 04:11

....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

查看更多
Explosion°爆炸
4楼-- · 2020-01-29 04:18

both seem to be working.

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

查看更多
\"骚年 ilove
5楼-- · 2020-01-29 04:19

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();
查看更多
仙女界的扛把子
6楼-- · 2020-01-29 04:27

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

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

Take a look

查看更多
Melony?
7楼-- · 2020-01-29 04:27

Actually, $('#id', this); would select #id at any descendant level, not just the immediate child. Try this instead:

$(this).children('#id');

or

$("#foo > #moo")

or

$("#foo > span")
查看更多
登录 后发表回答