Reputation: 201
I have a method that fires after page load. This method has the following string:
$jq('#myElement').myCustomFunction("some info", "sometext");
My functions take 2 parameters:
jQuery.fn.extend({
myCustomFunction: function (info, text) {
}
});
Can I pass to function or get inside a function the Id of an element? For the following example, it should be #myElement
Upvotes: 1
Views: 94
Reputation: 337570
The plugin executes under the context of the jQuery object which invoked it. As such you can use this.prop('id')
to read the id from the element.
jQuery.fn.myCustomFunction = function(info, text) {
console.log(this.prop('id'));
}
$('#myElement').myCustomFunction("some info", "sometext");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myElement"></div>
That assumes that you're only expecting/allowing the plugin to be called on a single element. If you're allowing it to be called on multiple (which you really should in order to follow jQuery best practice) then you'll need to loop through them all.
jQuery.fn.myCustomFunction = function(info, text) {
this.each((i, el) => console.log(el.id));
}
$('.foo').myCustomFunction("some info", "sometext");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo" id="myElement"></div>
<div class="foo" id="thisElement"></div>
<div class="foo" id="thatElement"></div>
Upvotes: 1