I'm trying to get the selector used to call the current script, but of course the property I need was removed for some reason.
Is there a workaround for this? Here's basically what I want to accomplish:
(function($) {
$.fn.myplugin = function(options) {
return this.each(function() {
console.log($(this).selector);
});
}
}(jQuery));
//Somwehere else:
$('.theClassISelected').myplugin(); //Should console.log('.theClassISelected')
I need to see .theClassISelected (or some form of the original selector I used to call the function) in the console, but since the selector property has been removed from jQuery, it doesn't possible anymore.
I don't understand why it was removed - I've Googled this problem for a while now and all I see are StackOverflow answers from 2011-2012 recommending the selector property. I guess it was useful at some point, but not anymore?
From the jQuery documentation:
Plugins that need to use a selector should have the caller pass in the selector as part of the plugin's arguments during initialization.
http://api.jquery.com/selector/
As an aside, the docs also mention that the selector property wasn't reliable since "since subsequent traversal methods may have changed the set."
Related
Now I learning Backbone and Marionette, I read some tutorial and I found a code whom I haven't understand. Here's the code:
$('element',this.el)[0]
I know jQuery little bit. I know this keyword, i know the $('element') keyword, but not understand that code, please everybody tell me about that.
This $('element',this.el) says select all <element> contained within this.el. this.el must be another "object" but what it is depends on what is building this higher up. I cover this in more detail in this answer to a similar question.
The [0] simply unwraps the jquery object returning a vanilla DOM object. So:
$('element',this.el).first(); //works
$('element',this.el)[0].first(); //will error
The second errors becuase it is no longer a jquery object so it is not wrapped in the jquery functions.
In Backbone context, your code is probably found inside a view and this.el refers to the view's element
$('element',this.el) find the element nodes inside the scope defined by this.el
$('element',this.el)[0] refers to the first element node found
Note that in a Backbone view, you can simplify to
this.$('element')[0]
This is the jquery selector context syntax:
'element' is to a selector and this.el is a context and using bracket notation to get the first element [0] which also converts jquery element to javascript object.
Alternatively you can use like this instead of jquery selector context syntax:
$(this.el).find('element')[0] // hope you understand this syntax
Hello this seems to be working on IE8 :
var clsName = link.parents("div.fixed_column").attr("class").split(" ");
if($.inArray("column_one", clsName)
While this one reports error (Object expected errror in jquery).
var clsName = link.parents("div.fixed_column").attr("class");
What is the right way to do this? I thought purpose of inArray was that jquery will handle cross browser issues.
Unfortunately, this is indirectly answering your question, but... You seem to be looking to detect if an element has a class, and since you're already using jQuery, just use the hasClass method - http://api.jquery.com/hasClass/
For your specific code, try:
if (link.parents("div.fixed_column").hasClass("column_one")) {
// It has the "column_one" class
}
The more immediate answer to your question is that link.parents("div.fixed_column").attr("class") returns a single string. When the jQuery selector (div.fixed_column) returns multiple elements, which is very possible when using classes, using jQuery methods that get information (like .attr, using one parameter...to "get" the value) return the first matched element's value only.
So say the selector matches 3 elements:
["<div id='div30' class='fixed_column div30_class'></div>",
"<div id='div2' class='fixed_column div2_class'></div>",
"<div id='div17' class='fixed_column div17_class'></div>"]
Then the value returned from .attr("class") will be: fixed_column div30_class because it's the first matched element.
I'm not sure, but I think you're expecting jQuery to return an array of all the matched elements' values, which it just doesn't. So that doesn't mean jQuery isn't handling cross-browser issues, it just means you need to look up what the method does/returns.
I could've sworn that jQuery 2.0 has options for doing what you want - directly from calling the getters (or something similar), but I can't find it anymore :( Maybe I'm remembering incorrectly. Anyways, you could easily use $.each and/or $.map to look at every matched element, but it depends on what you were really trying to do with it.
You can't read the attributes of multiple elements into an array with .attr("class"). But why don't you just target the desired class in the selector like this?
var cols = link.parents("div.fixed_column.column_one");
Then change your conditional to check for an empty set:
if(cols.length) { ...
I'm in the middle of writing a plugin and I'd like to be able to get the original selector that jQuery used to create the object.
So if you wanted to apply something like .siblings() you could get all the siblings of that type, whether it looks up siblings of a certain class or siblings of a certain element type.
jQuery('div') – 'div'
jQuery(jQuery('div')) – '[jQuery] object' // would require recursively finding the selector of this
jQuery('#elment') – '#element'
jQuery('.class') – '.class'
Just access the jQuery object's selector property:
console.log($("div").selector); // 'div'
console.log($("#foo").selector); // '#foo'
This no longer seems possible... '.selector' was removed in version 3 and jquery instead recommends passing in the selector twice.
https://api.jquery.com/selector/....
The .selector property was deprecated in jQuery 1.7 and is only maintained to the extent needed for supporting .live() in the jQuery Migrate plugin. It may be removed without notice in a future version. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set. Plugins that need to use a selector string within their plugin can require it as a parameter of the method. For example, a "foo" plugin could be written as $.fn.foo = function( selector, options ) { /* plugin code goes here */ };, and the person using the plugin would write $( "div.bar" ).foo( "div.bar", {dog: "bark"} ); with the "div.bar" selector repeated as the first argument of .foo().
As an extension to what Karim has put:
var t = jQuery('.clName');
t.each(function(){
jQuery(this).data('selector',t.selector);
});
Why is it when I select html elements using .get(i) or similar methods, I am unable to use methods on those elements like the .removeClass() or .html().
I would think that the code below is perfectly valid, yet neither lines work. What do I need to do to apply jQuery methods to an element based on its ordinal index in the DOM?
($('li').get(0)).removeClass('yourClass');
$('li')[0].addClass('myClass');
Here is an example of the issue: http://jsfiddle.net/KcNWy/2/
Check the documentation:
The .get() method grants us access to the DOM nodes underlying each jQuery object.
You can DOM object into jQuery object again: $($('li').get(0)). Or, better yet, use eq: $('li').eq(0).
And also a debugging hint. You can use in firefox/chrome/safari console.log(myObject) to see what's actually returned.
The get() method passes back the DOM object
Retrieve the DOM elements matched by the jQuery object.
Try this instead:
$("li:eq(" + 0 + ")").removeClass("yourClass")
Working example: http://jsfiddle.net/KcNWy/6/
Being fully self-taught without actually reading up on JavaScript (It's my job now, believe it or not) there are a few things I accept but don't understand.
The first one is the dollar sign.
As far as I use understand it, it's a shortcut to document.getElementById(),
but if I log $ and document.getElementById() to console - Only $ returns a value. This value however is always function(), shouldn't it be. The element? What gives?
The second issue I have is something that keeps coming up in my code and I go out of my way to change the code to eliminate it. It's the "... is not a function" error.
For example:
if ($.inArray($(div_id).val(), arr) >= 0);
Will give the error .val() is not a function. Why? And how do I use the value of div_id to see if it's in array?
Hiya. When you're using Jquery (which I assume you are), then $ will return the jquery object. This can contain an array of matched HTML elements depending on the selector you used. For example $("#foo") will return the jquery object containing the element with id foo. You can get the actual HTML DOM element out using $("#foo")[0] - using the array-style notation.
Can you give us some more info on what you're trying to achieve with the $.inArray example?
$ is a valid variable name.
So if you try to use $ without setting it, it will not work.
A lot of people/frameworks however use $ as a shortcut to document.getElementById, they would declare it at the top of the script as:
function $(id) { return document.getElementById(id); }
$ and document.getElementById is not one of the same thing. $ gives you a function in console only when you are using some library like jquery which mapes $ to a function.
.val id primarly used to get value of the form elements and that is a jquery function. I think you need to learn more around javascript and jQuery
Neither Javascript nor the DOM define $, which (as other answerers said) is often defined in general-purpose DOM libraries like jQuery, Prototype or Mootools. Based on the particular code you included, I suspect you've been coding against the jQuery API (because you use $.inArray, see http://api.jquery.com/jQuery.inArray/; though your claim that $ aliases document.getElementById confuses matters, as jQuery expects CSS selectors rather than element IDs).
When $ is expected but undefined, that usually means you'll need to include the library whose API you're using in the HTML document.