mare
mare

Reputation: 13083

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

Upvotes: 2

Views: 402

Answers (4)

user229044
user229044

Reputation: 239311

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"); });

Upvotes: 6

cjstehno
cjstehno

Reputation: 13984

Try

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

The context is the second parameter.

Good luck.

Upvotes: 1

rfunduk
rfunduk

Reputation: 30442

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);

Upvotes: 4

egyedg
egyedg

Reputation: 724

Try this:

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

Upvotes: 1

Related Questions