1

When making a jQuery plugin, is it possible to accept a text string instead of an element?

For example, instead of $("#someelement").myPlugin();: $('Some text string').myPlugin();

Also, is it possible to allow multiple parameters?

For example, $('Text here', 'Another text').myPlugin();

I have been researching, and $() seems to be used only for selecting DOM elements. However, it's not possible to not use it. When I tried my test function using just $.myPlugin(); it didn't work.

Therefore, for this kind of thing should I just use a function? Are jQuery plugins only used when targeting a DOM element (ie. the $("p").greenify(); example). Or is it acceptable to use them like a regular function with params?

1
  • 1
    Why would you want to wrap a 'text string' inside a jquery object? Don't use a plugin, use a function instead, see David's answer Commented Dec 19, 2013 at 10:53

3 Answers 3

3

jQuery "plugins" are just prototypes on the jQuery object. So when calling the constructor like $('text') it actually "does" something with the argument text (jQuery will treat this as a selector).

If you just want to create a "plugin" for manipulating text, here a simple one for you:

myPlugin('Text here', 'Another text');

Or you can extend the String prototype if you fancy:

String.prototype.myPlugin = function(suffix) {
    return this+suffix
};

'mytext'.myPlugin('.com') // -> mytext.com
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this info, I decided to just use a regular function.
1

you can design your plugin to accept a string as parameter...

and then use it on a jquery selection

$('#myid').myPlugin('some text');

or even just as a regular function

myPlugin('some text');

Comments

0

I don't understand your question - what do you want to do exactly?

If you want to call just the plugin without selecting a DOM node, most jquery extensions register themselves to $.fn: $.fn.my_pluginname

some possibilities to call it on an element:

$('#my-css-id').myPlugin(); 
$('<div class="justCreatedNow">content</div>').appendTo('body').myPlugin();

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.