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) { ...
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() );
});
What is Javascript alternative for this:
$('#clientDetailModal #heightValue')
I need it because in my code this works:
document.getElementById('heightValue').checkValidity()
but this doesn't:
$('#clientDetailModal #heightValue').checkValidity()
And I need to select only heightValue within clientDetailModal div.
Try $('#clientDetailModal #heightValue')[0].checkValidity()
The reason you need to do the [0] is, (as per the jquery id selector documentation)
Calling jQuery() (or $()) with an id selector as its argument will
return a jQuery object containing a collection of either zero or one
DOM element
Since you'll get a collection with 1 DOM element (assuming you don't have multiple ids), you need to then explicitly "select" that element using the [0].
You could use get to get the DOM element :
$('#clientDetailModal #heightValue').get(0).checkValidity()
Just to be sure, as your question might be a little ambiguous : only one element can have a given ID in HTML. So if your element is either absent or inside #clientDetailModal, then you could as well use
$('#heightValue').get(0).checkValidity()
It would also be faster. But in that case, there would be nothing wrong in using document.getElementById.
Since document.getElementById('heightValue').checkValidity() works, it means your function checkValidity() is attached on native DOM elements. This means, you can do:
$('#clientDetailModal #heightValue')[0].checkValidity()
Plus: If your HTML is valid with no duplicate IDs, you can simply do
$('#heightValue')[0].checkValidity()
Since the OP asked for a JavaScript alternative. On modern browsers,
document.querySelector ('#clientDetailModal #heightValue')
will return the element you are asking for.
The direct equivalent would be
document.querySelectorAll ('#clientDetailModal #heightValue')
which returns an array of elements matching the selector requested, do yrou will need to add the [0] as per the other answers.
I presume this is what you're looking for :
document.getElementById('clientDetailModal').getElementById('heightValue').checkValidity();
Libraries I've seen have DOM wrappers that inclusively handle only the first element of the list in some case, like:
return this[0].innerHTML
and use the whole list in some other like:
for( var i=0, l=this.length; ++i<l; ) this[i].className = cls;
return this
Why is this approach accepted?
I think singling out the first element defeats the purpose of having methods that apply the same thing on the rest of the list. Isn't it bad to have dubious functions? I know it suits many people..but it feels inconsistent and I'm interested in why this is accepted so widely.
EDIT as an example:
jQuery.html()
If the selector expression matches more than one element, only the
first match will have its HTML content returned.
why not all?
the hide() method in bonzo, from Dustin Diaz
//...
hide: function () {
return this.each(function (el) {
el.style.display = 'none'
})
}
why not only the first?
The accessor methods in jQuery return single values because it's simpler and more generally useful. If the .html() API were to return the value if innerHTML for all elements, that'd mean it'd have to return an array. That, in turn, would mean that in the most common case of wanting the contents of a single element, you'd have to add the array access. There's also the problem of knowing exactly which returned value goes with which selected element. In other words, if .html() returned an array of element contents:
var contentList = $('.someClass, span, .hidden .container').html();
If "contentList" were just a simple array, what use would it be? How would the code know for each element which DOM node it came from? Of course there are solutions to this, but again the simple case is made complicated in order to support a rare general case.
It's possible of course to get the list yourself with .map(). I think this is just an issue of smart, practical, pragmatic API design.
So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]
The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?
Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...
var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of
object[0].id
object.prop("id")
object.attr("id")
should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.
Your object is in fact a jQuery object, not a dom object.
To use the dom object use,
object[0].id
Or using, jquery, (Since it is already there)
object.prop('id');
You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id
See this for exemple: http://jsfiddle.net/cquuT/
In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property
object[0].id
I don't see a complete answer here, so I'll provide my own.
If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.
(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)
Universal solution to get ids of all elements returned by selector is:
.map(function(){ return this.id; })
Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]
To get id of the first element returned by selector use:
.attr('id')
Running $("div").attr('id') on current page will return "notify-container".
Since jQuery 1.6 you can also use .prop('id') here.
If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.
Is this:
var contents = document.getElementById('contents');
The same as this:
var contents = $('#contents');
Given that jQuery is loaded?
Not exactly!!
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
In jQuery, to get the same result as document.getElementById, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).
var contents = $('#contents')[0]; //returns a HTML DOM Object
No.
Calling document.getElementById('id') will return a raw DOM object.
Calling $('#id') will return a jQuery object that wraps the DOM object and provides jQuery methods.
Thus, you can only call jQuery methods like css() or animate() on the $() call.
You can also write $(document.getElementById('id')), which will return a jQuery object and is equivalent to $('#id').
You can get the underlying DOM object from a jQuery object by writing $('#id')[0].
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
A note on the difference in speed. Attach the following snipet to an onclick call:
function myfunc()
{
var timer = new Date();
for(var i = 0; i < 10000; i++)
{
//document.getElementById('myID');
$('#myID')[0];
}
console.log('timer: ' + (new Date() - timer));
}
Alternate commenting one out and then comment the other out. In my tests,
document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs)
On the other hand, the
jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).
From this simple test you can see that the jQuery took about 6 times as long.
Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo. But yes, technically getElementById is quite a bit faster.
No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents was matched.
The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value) etc, however you'll need to use jQuery methods on the jQuery Object.
var contents = $('#contents').get(0);
Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.
One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null returned by document.getElementById
No, actually the same result would be:
$('#contents')[0]
jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.
Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection
When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object
In case someone else hits this... Here's another difference:
If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.
This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:
var contents = document.getElementById('a/b/c');
was able to find my element but:
var contents = $('#a/b/c');
did not.
Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:
var contents = $('.myclass[name='a/b/c']);
var contents = document.getElementById('contents');
var contents = $('#contents');
The code snippets are not the same. first one returns a Element object (source).
The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById() for efficiency.
In both the cases if more than one element found only the first element will be returned.
When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.
Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.
<body id="content">
<h1>Header!</h1>
<form>
<div id="content"> My Form </div>
</form>
</body>
It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.
All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it
<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>
Online Demo!
- https://codepen.io/frank-dspeed/pen/mdywbre
jQuery is built over JavaScript. This means that it's just javascript anyway.
document.getElementById()
The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.
Jquery $()
Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.
All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :
I have an HTML :
<div id="contents"></div>
Go to console (cntrl+shift+c) and use these commands to see your result clearly
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:
$('#contents')[0]
>>> div#contents