I have two selectors
var allNodes = $("a.historyEntry");
var errorNodes = $("a.historyEntry.error");
I would like to to find a node before first error node, so I need to find an index of first error node, how to do it?
I tried to use inArray method, but it doesn't work for this
$.inArray(allNodes, errorNodes.first())
or
$.inArray(allNodes, $(errorNodes.first()))
Is there any fast way to do it in jQuery or do I have to use for loop?
index()?
It's like indexOf... but just without the Of... it returns the index of the element if it exists, and -1 if it doesn't.
Use index(). It does exactly the same thing as indexOf in java.
$.inArray value is the first parameter then the array:
$.inArray(allNodes, errorNodes.first())
should be:
$.inArray(errorNodes.first(), allNodes)
Example
Related
How do I get only one DOM element by class name? I am guessing that the syntax of getting elements by class name is getElementsByClassName, but I am not sure how many elements it's going to return.
document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array-like HTMLCollection returned.
var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];
Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.
// HTML
<div id="myElement"></div>
// JS
var requiredElement = document.getElementById('myElement');
Clarifications :
getElementsByClassName returns a Node List and not an array
You do not need jQuery
What you were looking for was probably document.querySelector :
How do I get only one DOM element by class name?
var firstElementWithClass = document.querySelector('.myclass');
Also see: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector
You can use jQuery:
$('.className').eq(index)
Or you can use the javascript built-in method:
var elements = document.getElementsByClassName('className');
This returns a nodeList of elements that you can iterate and make what you want.
If you want only one, you can access the elements in the javascript version like this:
elements[index]
To anyone looking for a one liner
var first = document.getElementsByClassName('test')[0];
Use NodeList.item().
For example:
var first = getElementsByClassName('test').item(0);
You can try with this:
document.getElementsByClassName("className")[index]
Here is my old code:
checkboxes = document.getElementsByName('foo');
As you know, checkboxes will be an array. Now I need to limit selecting scope. So this is my new code:
checkboxes = $('.myclass input[name=foo]');
But in this case checkboxes isn't an array anymore, it's a jQuery object. How can I make it the same as getElementsByName('foo')'s result?
Note that $('.myclass input[name=foo]')[0] won't work either.
Try .toArray()
checkboxes = $('.myclass input[name=foo]').toArray();
Use this
var checked = [];
$.each($("input[name='foo']:checked"), function(){
checked.push($(this). val());
});
Charlie already pointed out that jQuery objects have a toArray() function. That would work I think. Figured it was also worth noting that there is also a .makeArray() function for generally converting array-like objects to native JavaScript arrays. https://api.jquery.com/jQuery.makeArray/
You can use .map() and create an array of underlying DOM which getElementsByName() returns
checkboxes = $('.myclass input[name=foo]').map(function(){ return this;}).get();
I would recommend #Charlie answer
You don't need to convert to Node elements array. Change your function to
function toggle(source, target) {
$(target).find('input[name=foo]').prop('checked', source.checked);
}
Usage
toggle(source, '.compare_people')
toggle(source, '.compare_posts')
document.querySelectorAll("input[name=foo]")
Getting javascript object from jquery object by $('selector')[0] should work. See the answer from this link How to get javascript control from JQuery object?
I suspect your selector is the reason why the above approach doesn't work. Add double quotes to name value will make it work:
checkboxes = $('.myclass input[name="foo"]');
Could someone tell me what the jQuery equivalent of this would be?
var shapes=document.getElementsByTagName("shapes")[0];
thisCircle=shapes.getElementsByTagName("circle")[index];
There are a few ways to do it. Here's how I'd write it:
$('shapes').first().find('circle').eq(index)
You can just use the tags directly in the CSS selector and use modifiers like :first to let the CSS selector engine do most of the work for you and to create the fewest intermediate jQuery objects.
.eq(index) selects the index item from all the items found and returns a jQuery object. Directly indexing it with array syntax like [index] will return a DOM object (not a jQuery object):
$("shapes:first circle").eq(index)
The step by step description of what is going on here is this:
Find the first shapes object.
Find all circle objects that are descendants of that first shape object and construct a jQuery object that contains all those circle objects.
Call the eq() method on the jQuery object to make a new jQuery object that contains only the index circle object (e.g. only the 3rd one).
$("shapes:eq(0) circle").eq(index);
$('shapes').eq(0).find('circle').eq(index)
I think this should work:
$('[name="shapes"]').first().find('circle').eq(index);
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) { ...
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.