Given the following code, why does the selector property work in the first instance but not the second? Aren't they both jQuery objects?
<span class='tst'>span</span>
var tst = $('.tst');
console.log(tst.selector);
// prints '.tst'
$('.tst').each(function() { console.log(this.selector);});
// prints undefined
this, in the context of the .each() loop, is not a jQuery object, so the selector property is undefined.
You need to make it a jQuery object first: $(this).selector
However, it should be noted that the selector property will return an empty string while inside the .each() loop.
Edit
If you absolutely need the selector property within the .each(), one option would be to cache your selector:
var cached = $('.tst');
cached.each(function() {
console.log(cached.selector); // Will display ".tst"
});
this != $(this)
In your first case tst is a reference to the jQuery object, but in the second this is simply the corresponding DOM element.
Within an .each() loop the .selector property is not available, however. To access '.tst' you can do $(this).attr("class") (when you use a class selector) -- though if you already use it in the each you can just cache it in a variable before hand.
Note that this will return all of the classes for that elements, so you can parse it later if it has more than one.
The best workaround based on your exact description is this:
var $tst = $(".tst");
$tst.each(function() {
console.log($tst.selector); //prints .tst
});
However I can't see any reason why you really need to do this.
Working Demo http://jsfiddle.net/wA6Yv/ or http://jsfiddle.net/a3CYR/2/
this != $(this)
If you keen: jQuery: What's the difference between '$(this)' and 'this'?
code
var tst = $('.tst');
console.log(tst.selector);
// prints '.tst'
$('.tst').each(function() {
alert($(this).text());
});
// prints undefined
Related
I'm having trouble getting to the source of this problem. Basically the error message I am getting in my console is:
TypeError: $(...).getElementsByTagName is not a function
When I click through to the line it is occuring on it is here:
var inputs = $('directoryresults').getElementsByTagName('input');
I'm not sure why this is happening as I have included jQuery in the header of the page itself:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
Does anyone have any ideas what might be causing this?
Does anyone have any ideas what might be causing this?
The object returned by the jQuery constructor doesn't have the .getElementsByTagName() method.
$('selector') returns a jQuery object. .getElementsByTagName() is a native JavaScript method of DOM elements.
To look for elements with a certain tagname using the jQuery object you currently have:
var inputs = $('directoryresults input');
// OR
var inputs = $('directoryresults').find('input');
To get a like-for-like node list that .getElementsByTagName() would return (note this isn't exactly the same, this will return an array where .getElementsByTagName() will return a HTMLCollection):
var inputs = $('directoryresults input').get();
Note: directoryresults, I am assuming, is either a class or id of a DOM element. Either way you'll want to amend the selector above
getElementsByTagName is a method you will find on Element and Document objects.
$('directoryresults') will return a jQuery object (containing any <directoryresult> elements … so nothing if you are working on an HTML document).
to use getElementsByTagName, you need to extract the elements from the jQuery object:
$('directoryresults')[0].getElementsByTagName
The above will only get the first element from the jQuery object (and it assumes that there will be at least one element) so you should probably replace the hard coded [0] with a for loop.
That said, you should generally use the find method instead:
$('directoryresults').find('input')
… or just use a descendant combinator in the first place:
$('directoryresults input')
As noted earlier, directoryresults won't find anything in a valid HTML document. You probably want to prefix it with . or # depending on what you are actually trying to match.
You are ussing a DOM API mixed with jQuery API sintax:
it's document.getElementsByTagName('input');
The first error is not specific if directoryresults is a class or an ID
Nor do you tell if a target item or the item you wish to call
If you use jQuery by TagName type this:
var inputs = $('input');
if you want put values in a div
$.each(inputs, function(){
$('div').append( $(this).val() );
});
I'm working on a jQuery widget that attaches events to the widget's parent, but I'm unable to tell if it has a parent.
For example;
var x = $('<div>');
x.mywidget();
........... in mywidget
_create : function () {
var y = this.element.parent() === undefined ? this.element : this.element.parent();
y.bind(....);
}
I need to check if the widget has been added to the DOM before I do the bind statement. If it has not been added to the DOM, then I'll just bind this.element.bind(....) instead.
The problem is that $('<div>').parent() returns a jQuery object! I was expecting that it would return undefined.
So I'm wondering what parent could it be returning when it shouldn't have a parent?
You may use myDiv.parent().length to know if the jQuery set is empty or not.
But this will yield false positives if the object wasn't removed from the DOM directly but it parent was.
If you want a reliable detection, then, you should use jQuery.contains(document.documentElement, myDiv).
It will always return an object. If you want to see whether anythings in the object, you can check for .length == 0, so $("<div>").parent().length == 0 would be your check.
Check the length of the jQuery object returned. If your div has no parent, the jQuery object returned by .parent will wrap zero elements.
All jQuery DOM searching and manipulation methods return a jQuery collection with 0 or more elements. $("<div>").parent() returns a collection with no elements (an empty collection). You can still call any jQuery method on it, but without being tied to a DOM element what you can do is very limited. It will have .length of zero, and the callback will not be reached when iterating over with .each.
I would check the length of the jQuery object since jQuery will always return an object.
it will be always a parent, can be the body for example
use jquery data for example to set your init marker
var wasInit = ( $(this).data("mypluginwasinit") !== undefined );
if(wasInit) return;
$(this).data("mypluginwasinit","yes");
$(function(){
var z = document.body.children[0];
var x=$("li", z);
x.name="Johnny";
alert(x.prop(name));
});
x should be an object containing all the elements within the first ul in the body.
Regardless of what the object contains, I would like to add a property with a value, and then use the prop() method to show it - but that doesn't seem to work. Why is that?
I saw a script containing the following: var $x = $("div"); - Do I have to add $ to the variable name if it's a jQuery object?
To select the first ul element inside a page you can do:
$("ul:first li")
This way you are going to select all lines inside the first list in the page.
To store arbitrary data in an element you can use the method data, like this:
$("element").data('key', 'value');
and to retrieve the data:
$("element").data('key');
More info, for the data method.
If you really want to add an attribute you can use the attr method, it works the same way as the data method, but it would reflect in the DOM.
If you want all li elements in the first ul element, then this should do the trick:
var elements = $("ul:eq(0) li");
Here is a very simple example of this in action.
In regards to setting a property, you can do element.name = "test" and it will work ok. But what you need to understand is that this is setting a name property on the jquery collection object and NOT on any of the actual elements.
What you can do however, is set the property like so:
elements.prop("name", "test");
and the access it like so:
var name = elements.prop("name");//name will be "test"
Here is a working example
As I mentioned in my comment, you don't need to prefix the variable with $. But this can be helpful to easily see which variables are JQuery objects.
Number 1. x is a jQuery object, you added to that instance a name property, then you're using name though it wasn't defined.
If you want to change a property of the element you got with jQuery the ways are:
$('selector').prop('property', 'value');
$('selector').attr('attribute', 'value');
$('selector').get(index).property = "value";
Number 2. no you don't have to, $ prefix is simply a convention to make the code more readable.
Is there any specific reason behind using $ with variable in jQuery
Using the selector from #musefan answer, you can take the collection returned, and use the attr() method to add an attribute and value to each item selected. However, I've modified his selector slightly to actually grab "all" elements in there, (just in case future visitors wonder)
var elements = $("ul:eq(0)").children();
elements.attr("attrName", value);
So if you wanted to set the title:
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny");
You probably don't want to alert these values, browsers may ask you to stop allowing alerts on the page... but if you really did, then you could throw in an .each() after that.
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny").each(function(){
alert($(this).attr("title");
});
I'm writing a general purpose helper function in JavaScript. It accesses the className property of the element.
But since I'm using jQuery, it turns out that sometimes the element passed as an argument is actually an array (a jQuery set).
What is the simplest way to use an argument if it's an element or get the first element from the set if the argument is a set? Does jQuery have a tool for this?
You can test if the object is a jQuery object by using instanceof:
if (myObject instanceof jQuery) {
// use $.each to loop over myObject and get class names of all
// or just use myObject[0].className to return only the first
} else {
// it's not a jQuery object
}
You always want a native element? Each jQuery object has a property jquery (containing the jQuery version) so you can use it to check if the element you got is likely to be a jQuery object:
obj = obj.jquery ? obj[0] : obj;
If you are not into ducktyping:
obj = (obj instanceof jQuery) ? obj[0] : obj;
In case you want to pass a single element, an array of elements or a jQuery object to the same method, do the following:
function stuff(element) {
element = [].concat(element)[0];
}
If you have to deal with both jQuery objects and non-jQuery elements, this is a bit tougher. Keep in mind that the jQuery collection can possibly have different classNames for each element, i.e. the first and others may not be the same.
It's slightly inefficient, but this will work:
function (obj) {
var className = $(obj).get(0).className;
}
Wrapping a jQuery object in jQuery() does nothing, but wrapping the element allows you to access it again via .get. It's inefficient because you may have an extra $() call.
If that's no good, you could check obj.hasOwnProperty('className') since a jQuery object usually should not have it, but I think that is riskier.
Is a jQuery Object an Element or an Array of Elements?
Strictly, neither.
A jQuery object is a Javascript object that has some of the Array capabilities. In most aspects you can use it as an array of elements.
If the jQuery object may contain several elements, and you only want the first, you can use the first method to get that:
elements = elements.first();
If the parameter can be either an element, an array of elements, or a jQuery object, you can wrap it in a jQuery object to handle all the cases:
elements = $(elements).first();
I have a function that gets passed the document object like:
toggle( $('username') );
function Toggle(id)
{
/// ??
}
How can I get the actual name of the object passed i.e. username?
If I understand you correctly, can't you:
$(id).attr("id");
or
$(id).attr("name");
Or am I mistaken?
Either what Jonathon said or with
$(id).val();
The object that gets passed in is an instance of the jQuery object, which contains a set of elements (in this case with only one element in it). The documentation is on the jQuery documentation site.
The jQuery object that $() returns, wraps one or more DOM elements.
Using the accessors $().attr(), $().val(), $().text() and $().html() will act on the first of those wrapped elements.
If you want to drop out of jQuery mode so that you can work with the native DOM element (sometimes useful) use $().get( index ).
eg
var el = $('#mytextbox').get(0);
el.value = 'a new value';
alert(el.id);
etc...