开发者

jQuery context selection

If I do this

var domElement = $("#id");

and the returned element is a div tag,

How can I then do something like

domElement.$('div a:nth-child(3)').after(somehtml);

This is an example where I want to add some HTML after the third link under that "domElement" div.

The above doesn't seem to work. I have numerous examples where I have already selected a certain element from the entire page 开发者_StackOverflowHTML and I then want to work inside the "context" of that element.

In 90% of cases I want to continue jQuery selection, traversion and manipulation from a previously selected DOM element from a page not from the whole page like $(..) does.


You want .find(): http://api.jquery.com/find/

var domElement = $("#id");
domElement.find('div a:nth-child(3)').after(somehtml);

If you plan on chaining this with multiple sub-selectors on domElement, end each use of .find() with .end():

$("#id")
  .find('div')
    .click(function() { alert("#id div"); })
    .find('a.my-class1')
      .click(function() { alert("#id div a.clickable"); })
      .end() // stop working with 'a.my-class1'
    .find('a.my-class2')
      .click(function() { alert("#id div a.my-class2"); }) 
      .end() // stop working with 'a.my-class2'
    .end() // stop working with 'div'
  .click(function() { alert("#id"); });

Conceptually, you're descending deeper into the DOM with .find(), and ascending back up the DOM with .end(). Technically "descending" and "ascending" aren't correct because you can also traverse first up then back down with functions like .parent() or .closest(), both of which can be terminated with .end() to return to the original selector:

$("#id")
  .parent()
    .click(function() { alert("I'm #id's parent!"); })
    .end()
  .click(function() { alert ("back to #id"); });


Two options, use the context argument to the jQuery function:

$('div a:nth-child(3)', domElement).after(something);

or (my preference) use find:

domElement.find('div a:nth-child(3)').after(something);


Try this:

$('div a:nth-child(3)', domElement).after(somehtml);


Try

$('div a:nth-child(3)',domElement).after(somehtml);

The context is the second parameter.

Good luck.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜