33

Okay, normally I would consider myself an intermediate user of jquery, but this seems like a very noob issue that I'm not quite sure how to code.

I have one div that I want to run a function against. The only way I'm aware of how to do this is something like...

$("#divname").each(function(){
  dostuff();
});

This seems like a bit more work when I know there will only be one element. I tried this...

$("#divname", function(){ 
  console.log($(this));
});

... but it writes out the whole dom. I just want to run the function on this one element. How do I do that?

5
  • @JonathanSampson. LoL, My answer would have been exactly the same if there wasn't 30 chars answer limit... :) Commented Jun 7, 2012 at 14:55
  • @gdoron It's actually not the best approach. It prevents you from using doStuff as a callback later on in other jQuery iterations since you refer to a parameter rather than this. See my answer for details. Commented Jun 7, 2012 at 15:14
  • @JonathanSampson. It depends on what the OP wants do. He didn't mention what exactly does he want to do. Commented Jun 7, 2012 at 15:16
  • @gdoron He showed doStuff in a call to each, so I assume it's a function he wants to be able to run on many items, but also run explicitly on one item. Commented Jun 7, 2012 at 15:17
  • @JonathanSampson. I upvoted already as it was better than mine. But I do suggest the OP to give more context in his questions, knowing we are not sitting next to him or having crystal ball could help even more. :) And by the way, it looks like he accept my style answer and not yours... :) Commented Jun 7, 2012 at 15:19

2 Answers 2

28

You should call the function, passing your element in as its object:

function doStuff() {
    alert( $(this).html() );
}

doStuff.call( $("#foo")[0] );

Due to the way we built and call doStuff, we can still use it as a callback on .each:

$(".bar").each( doStuff );

Fiddle: http://jsfiddle.net/jonathansampson/WuyJc/

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

Comments

21

If you maintain that each element in HTML DOM has unique id that means no two elements have same id, then $('#divname') always return a single element and $('#divname').each() will run one time. not more than one.

Now in your case you want something like

dosomething( $('#divname') );

For example:

function doSomething( el ) {
   el.append('<span>hello</span>');
}

 doSomething( $('#divname') );

DEMO

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.