Hooch
Hooch

Reputation: 29673

jQuery run function in context of element

I have some function that (for example only) looks for all divs and appends to them.

function test() {
    $('div').append(/*...*/);
}

Now I'm loading new divs via $.get function to my container element. After loading of new divs I want to call test() function in contex (limited to) my container element. I only want to append sth to new divs. I dan't want to append twice to old divs.

I don't want to edit test function if it is possible.

Upvotes: 0

Views: 598

Answers (2)

Shmiddty
Shmiddty

Reputation: 13967

function test(container) {
    $(container).find('div').append(/*...*/);
}

used like:

test("body");
test("#mainContainer");
test("ul.spiffy > li");

In short, you simply pass in the selector that you want to modify divs inside.

If you want to allow for a "default" value, you can do something like this:

function test(container) {
    if (container == undefined) container = "body";
    $(container).find('div').append(/*...*/);
}

Now, if you pass no parameter to test, it will apply the append to all div elements inside of body.

Upvotes: 1

Korikulum
Korikulum

Reputation: 2599

$('div', 'container').append(/* code */);

Upvotes: 0

Related Questions