jQuery get searched selector, if element doesn't exist - javascript

If an element doesn't exist, how do I get a string of the selector that was searched?
For example:
$( 'parent child.class' ).plugin( )
In my plugin, I want to get the string "parent child.class", but $( 'parent child.class' ) doesn't exist.
I'm going to start digging through the jQuery source code, but I figured I'd ask in case someone with more intimate knowledge knows this.

You can't.
jQuery objects have a .selector property, which you could use within your plugin (though it seems to be intended for use interally with jQuery), but - and it's a big but - not all jQuery objects are created with a selector string. Consider this example use of .yourPlugin():
$('div.someClass').add(document.getElementById("test"))
.add("<div>Hello</div>")
.filter(function() {
return $(this).attr("data-test") == "blah";
})
.parents()
.yourPlugin();
It doesn't make sense to be thinking about what selector resulted in the jQuery object eventually passed to .yourPlugin(), regardless of whether it contains any elements.
(I suppose if you know your plugin will only ever be used by you and you'll only ever pass it jQuery objects created with a selector then you could use this.selector within your plugin...)

there is selector property:
$.fn.plugin = function() {
if (this.length == 0) {
return this.selector;
}
};

Related

jQuery objects and elements

I know I've seen a beautifully straightforward answer to a similar question before, but I haven't been able to remember or locate it, so apologies in advance.
I'm not new to coding, but I've had no formal training with Javascript/jQuery. Everything else I used has been strictly typed, so I'm still struggling with how JS does typing. I have a function that fires every time a child of a specific class is changed (I'm writing this for Sharepoint, so there is some working-around that has to be done.)
Why is it when I write this:
$(".listen *").change(function(event) {
var element = event.target;
if (element.title == 'Workstation')) {
alert(element.val());
}
}
I get an error that .val() is not a function, and I have to instead write
$(".listen *").change(function(event) {
var element = event.target;
if (element.title == 'Workstation')) {
alert($('#' + element.id).val());
}
}
What is the difference between the object that "element" is and the object retrieved by using the id? Aren't they both jQuery objects? I realize that not all objects returned by my function might actually have a value to return, but I don't understand how the distinction is being made.
Thanks!
In your first code block the 'element' variable is not a jQuery object, it is a DOM object. The .val() method is not defined for DOM objects. It is only defined for jQuery objects.
In your second code block $('#' .element.id) returns a jQuery object that does have the val() method defined.
So to answer your question, No they are not both jQuery objects, only the second one is.
You must make jQuery object from your dom (event.target) like that;
$(".listen *").change(function(event) {
var element = $(event.target);
if (element.attr('title') == 'Workstation')) {
alert(element.val());
}
}
Then you can use your jQuery object as you want. By the way, if you want to catch the changed element, you can use $(this) instead of $(event.target).
$(".listen *").change(function(event) {
var element = $(this);
if (element.attr('title') == 'Workstation')) {
alert(element.val());
}
}

jQuery / JavaScript, why do I need to wrap variables in $() to use them?

Say I have a map on an array of elements. The callback function takes the index and the value at that position in the array.
If I wrap the array element that the callback receives in $(), it behaves as I expect. If I use it without wrapping it in $(), it gives an error.
var nonHiddenElements = $( "form :input" ).not(':hidden');
nonHiddenElements.map(function(index, element){
input_id = $(element).attr('id'); // this works
input_id = element.attr('id') ; // this gives an error
})
Can someone explain how this works.
Is this a jQuery quirk, or a JavScript thing?
What type of objects does my nonHiddenElements array contain exactly?
What is element that gets passed to the callback?
And mainly what is the $() doing?
You need to understand how jQuery actually works. I will try to explain it briefly.
$ is nothing but a normal javascript function. jQuery === $, is just a function with a fancy name. This function does a lot of different things, depending on what you pass in it. For example if you pass a string it will be treated as CSS selector and jQuery internals will try to find corresponding DOM elements. Or if you pass a string starting with < and ending with > jQuery will create a new DOM element by provided HTML string.
Now if you pass a DOM element or NodeCollection of DOM elements, it/they will be wrapped into jQuery instances so that they can have a jQuery prototype methods. There are many prototype methods jQuery offers. For example text, css, append, attr - those are all methods of jQuery prototype. They are defined basically like this (simplified):
jQuery.prototype.text = function() { ... }
Normal DOM elements don't have those convenient methods jQuery provides. And inside of methods like map or each if you check this value or element parameter like you do, you will see that they are actually not jQuery instances:
element instanceof jQuery // => false
and of course you can't use instance methods with not an instance.
So in order to use jQuery prototype methods you need have a jQuery instance, which you can obtain if you call jQuery function with DOM element passed in it:
$(element) instanceof jQuery // true
Javascript is a programming language.
jQuery is a JavaScript Library.
With jQuery:
$("some element")
In native JavaScript you would have to do something like this.
getElementById('elementByID')
Explained in detail here: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
MDN is a great resource for beginners. https://developer.mozilla.org/en-US/docs/Web/JavaScript

jQuery 1.9.1 property selector

Background
As of jQuery 1.9 the .attr(..) method no longer returns property values, instead we now have to use .prop(..). Unfortunately this also applies to attributes specified via an attributes selector i.e. $("input[value=]")
See
http://jquery.com/upgrade-guide/1.9/#attr-versus-prop-
and a good SO discussion on the differences between .attr and .prop :
.prop() vs .attr()
My Situation
I'm currently using selectors like $("input[value=]") and $("select[value=]")
to select input elements that have no value set. However, this no longer works with jQuery 1.9, instead I'm now doing something like this:
var hasValue = function () { return !!($(this).val().length); };
var hasNoValue = function () { return !($(this).val().length); };
$("input").filter(hasValue);
$("select").filter(hasValue);
My actual selectors are a little larger, checking multiple elements with or without values so now I'm having to split my 1 selector string into multiple selectors with .filter(..) method calls in between.
Question
Is there an equivalent to $("[value=]"), $("[value!=]"), $("[value='abc']") which uses the property instead of the attribute? And if not, is there a cleaner way than using the .filter(hasValue) and .filter(hasNoValue) methods?
Thanks
Using .filter seems to be the only way, but it's not too bad and you can actually make it a little more accurate by using .val:
$(":input").filter(function () { return $(this).val() === ""; });
If this really is that reprehensible to you, you could create a custom selector.
$.expr[':'].emptyInput = function (elem) {
return $(elem).is(":input") && $(elem).val() === "";
};
http://jsfiddle.net/ExplosionPIlls/zaZPp/
EDIT: You may also be able to get away with using this.value instead of $(elem).val().
According to the upgrade guide:
However, when a selector like "input[value=abc]" is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.
So this answers your first question - there is not a direct equivalent, the point is to use the attribute instead of the property.
Your code seems fine, but if you want to be more standardized and re-usable you could create an additional filter. Like so:
(function($) {
$.expr[':'].hasValue = function(element) {
var $element = $(element);
return element.is(':input') && element.val();
};
}(window.jQuery));
This will allow you to select stuff like that:
// Select input elements with value and select elements without value.
$('input:hasValue,select:not(:hasValue)');
And other various combinations you need.
I came across this and just wanted to post another solution I found that works in some situations where some of the other suggested solutions are not appropriate.
Simply add this event handler to your code
$('input').on('keyup', function(){
var value = $(this).val();
$(this).attr('value', value);
});

Using javascript "this" for jquery selector

In this code, we can obtain value of element id as 2 differnt way and both way return resultat
$("#my_div").on("click", function () {
alert( $(this).attr("id") );
alert( this.id );
});
But i interest, second way, is it proper in this case? I ask this, because in code we use jquery selector and for jquery selector, write clear javascript: this is justified and will it work always? or may be better use jquery $(this) for jquery selector? or not differnce?
this.id will give you the internal DOM element property while $(this).attr("id") returns the value of 'id' attribute.
The alternative to this.id in jQuery is using prop() method: $(this).prop("id"). However, using pure this.id construction will be easier and faster.
The main jQuery constructor can take a number of different types of argument.
In that context, this is not a selector, it is an HTMLElementNode (which jQuery calls an element).
This is perfectly OK and documented.
There is no need to spend the resources in wrapping an element in a jQuery object if you are just going to grab its ID. There aren't any compatibility problems between browsers for that.
Grabbing the id property of an HTMLElementNode takes less code and is faster then wrapping the whole thing in jQuery.
Yes, your second way is proper.
$("#my_div").on("click", function () {
// this is available within this function
alert( this.id );
});
this refers to an HTMLDOMElement within the function, and wrapping that this within $() will give you an jQuery object.
If you define another function within the click handler. Ex:
$("#my_div").on("click", function () {
// keep reference of this
var that = this;
function test() {
// this will not available here directly
// instead of that you can use reference
alert(that.id);
}
});
And $(this).attr('id'), this.id or $(this).prop('id') will give you the same result.
For choosing the best method is not always clear.
In this case you want the this.id, because the other solution requires much more calls behind the scenes (obvious calls to jQuery and attr).
If you need more information that mite differ from browser, you want the jQuery way.

Determining what the selector is?

I jumped throught the different areas of jQuery source that are called when you type:
$('.foo')
or
$('#foo')
to try and determine how jQuery parses the selector ( I assumed charAt() ) but wanted to verify.
I got to here:
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
But I got kind of stuck on what
selector.nodeType
does. This reference says that a nodeType can be pretty much anything...so what exactly are they checking for?
The jQuery API breaks down the possibilities further.
In summary what is this code snippet trying to accomplish regarding the selector variable?
nodeType suggests that the object passed to the jQuery selector is a DOM node (which will generally be an element). This allows, for instance, the following construction:
$(document)
document is an object that represents the document. $(document) builds a jQuery object based on that element. The test for nodeType means that jQuery can detect whether the argument was an element, and if so simply to build the selection based on that.
You can also see this with the common construction $(this):
$('a').on('click', function() {
console.log($(this).text()); // builds a jQuery selection based on the this
// object, which is the DOM element that was
// clicked
});

Categories