0

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.

3
  • do you have some parent div for new divs? Commented Sep 11, 2012 at 22:06
  • $('div') selects all <div> elements. You'd have to modify your selector to $(parent, 'div') and provide a parent argument to test. Commented Sep 11, 2012 at 22:07
  • you will have to edit test function if it's selector is 'div' Commented Sep 11, 2012 at 22:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there really no way to limit it without modifying that function?
@Hooch Correct. But doing it this way will provide flexibility.
@Hooch tough luck? Without modifying that function, you can't change how it behaves.
How can I add default argument? I mean. If I pass nothing I want it to apply to whole document. Then I'll accept answer.
0
$('div', 'container').append(/* code */);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.