开发者

Selecting a variable's nested elements - jQuery

开发者 https://www.devze.com 2023-04-05 18:32 出处:网络
I wish to pass a variable to a function and have the function select elements within that variable. I\'m unfamiliar with the syntax of this case however, could any one advise?

I wish to pass a variable to a function and have the function select elements within that variable. I'm unfamiliar with the syntax of this case however, could any one advise?

For example, when a button i开发者_JAVA技巧s clicked within a container I wish for that container to be stored in a variable, okay I have that part. But then I wish to select a certain element within that container like

$(container "div#element");

How can you combine the two, noting that these elements could be deeply nested?


jQuery gets a second parameter, which determines the scope of the selection. For example $('#first-name', '#registration-form') only matches elements with the first-name id inside registration-form.

I guess you can use this feature. I think $("div#element", container); would work.

See this fiddle.


For chainability you can also use:

$(container).find('#element');


Use find if you are searching the Dom.

function doSomething(container) {
  var $element = $(container).find('#element');

  // .. Now do something

}

Use filter if you are wanting to search only the elements contained by container.

function doSomething(container) {
  var $element = $(container).filter('#element');

  // .. Now do something

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号