Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling function on jquery selector

Tags:

jquery

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?

like image 579
geoff swartz Avatar asked Jun 07 '12 14:06

geoff swartz


People also ask

What is $( function () in jQuery?

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });

What does a jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).

Which jQuery method triggers or binds a function to the error event of selected elements?

jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.


2 Answers

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/

like image 97
Sampson Avatar answered Sep 23 '22 13:09

Sampson


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

like image 44
thecodeparadox Avatar answered Sep 25 '22 13:09

thecodeparadox