How to handle multiple instances of a single class in jQuery? - javascript

I'm not exactly sure how to handle multiple instances like this. I know in normal JS I can simply use [0] and such.
My code is this:
location.href = $('a.test').attr('href');
I need to handle both the first instance of test and the second. Is there a simple
location.href = $('a.test')[0].attr('href');
I'm missing or such?

$('a.test')[0] return a dom element reference which does not have the method attr(), so your script will fail
use .eq(index)
location.href = $('a.test').eq(0).attr('href');
or
location.href = $('a.test:eq(0)').attr('href');

You are trying to call attr on javascript DOM object instead of using jQuery object as indexer returns the DOM object Use eq() to get jQuery object
location.href = $('a.test').eq(0).attr('href');
You can use DOM object with href instead of attr
location.href = $('a.test')[0].href;

location.href = $('a.test').eq(0).attr('href');
or you can try
location.href = $('a.test:eq(0)').attr('href');
reference eq() and :eq() and attr

This demo might help: working demo http://jsfiddle.net/CmQGu/
you can also use nth-child api demo here: http://jsfiddle.net/wYdyJ/
There are many ways you can approach this, like I showed you in demos. also if you keen read this : Difference between .eq() and .get() and :nth-child()?
API:
first : http://api.jquery.com/first/ (All the peeps up have missed this)
eq : http://api.jquery.com/eq/
nth-child : http://api.jquery.com/nth-child-selector/
Code:
alert(location.href = $('a.test').eq(0).attr('href'));
alert(location.href = $('a.test').first().attr('href'));
alert(location.href = $('a.test:nth-child(2)').attr('href'));
Hope it helps :)

Related

How can I use ".attr('disabled', false)" to btn[0]? [duplicate]

I'm new to jQuery, apologies if this is a silly question.
When I use it find an element using the id, I know theres always one match and in order to access it I would use the index [0]. Is there a better way of doing this?
For e.g.
var gridHeader = $("#grid_GridHeader")[0];
You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.
.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)
$("#grid_GridHeader:first") works as well.
You can use the first method:
$('li').first()
http://api.jquery.com/first/
btw I agree with Nick Craver -- use document.getElementById()...
http://api.jquery.com/eq/
$("#grid_GridHeader").eq(0)
You can use the first selector.
var header = $('.header:first')
With the assumption that there's only one element:
$("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()
...are all equivalent, returning the single underlying element.
From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
You can try like this:
yourArray.shift()

getAttribute method with jquery object

I am using filter to return a particular element. I want to know why .getAttribute is not working with returned object while it is working fine with .attr(). jsfiddle
var c = $('ul li').filter(function(){
if($(this).text()=='d')
return this;
});
console.log(c.getAttribute('value'));
You are mixing javascript with jquery. getAttribute is a javascript function.
try this
console.log(c.attr('value'))
Or simple
console.log(c.val())
.getAttribute() is a method associated with DOM object not with with jQuery object.
If you want to use it you need to get DOM object like
console.log(c[0].getAttribute('value'))
or
console.log(c.get(0).getAttribute('value'))
var c is array object and not single object. Use index like below :
console.log(c[0].getAttribute('value'))
^--- 0 index
JSFiddle

getElementById vs $('#element')

Before today, I thought that getElementById and $('#element') accomplished the same thing. However, when I tried the following:
// Assuming I have jQuery imported already
var $scrollHolder = $('#element');
var scrollDiv = document.getElementById("element");
scrollDiv.scrollTop = scrollDiv.scrollHeight;
//$scrollHolder.scrollTop = $scrollHolder.scrollHeight;
The commented line didn't work, and the uncommented line did. Do the two methods listed above return different things, or is there an error in my code? Should the commented line be working? I'm very confused and would appreciate insight. Thank you.
you have to get the DOM element from jQuery Object
$scrollHolder[0].scrollTop = $scrollHolder[0].scrollHeight;
or
.get( index )
$scrollHolder.get(0).scrollTop = $scrollHolder.get(0).scrollHeight;
$('#element'); is jQuery Object. It creates an array of matched Objects . But here you have id-selector so you only get one Object you can refer to the Native DOM object by using array index [index] or using .get(index).
document.getElementById("element"); is a native DOM Object
FYI
jQuery way of doing it.
.scrollTop()
.prop()
$scrollHolder.scrollTop($scrollHolder.prop('scrollHeight'));
$('#id) returns jquery objects which doesn't have native DOM properties and document.getElementById('id') returns you a native DOM element which has scrollTop property.
Note that you can make any DOM element act as jquery object by wrapping it with $( ) and you can make jquery object to DOM element by accessing index.
An other solution is using the correct jQuery-Wrapper for that:
$scrollHolder.scrollTop($scrollHolder.scrollHeight);
JQuery selector method always returns an Array of elements.
So commented line will not return what you expect.

jQuery selector with string object not working

var theHTML = '<html><head><title>Hi</title><link rel="apple-icon-touch-precomposed" href="icon.jpg" /></head><body></body></html>';
alert($(theHTML).find('link[rel="apple-icon-touch-precomposed"]').attr('href'));
It alerts "undefined." I want it to return "icon.jpg". What is wrong?
Try this:
alert($(theHTML).filter('link[rel="apple-icon-touch-precomposed"]').attr('href'));
That is, use .filter() instead of .find().
Demo: http://jsfiddle.net/WmwRU/
If you do a console.log($(theHTML)) you'll see why.
You'll need to use .filter() not .find() when selecting on HTML like that.
JSFiddle
I don't know what you want that for, but if you use filter() instead of find() it'll work as you want:
var theHTML = '<html><head><title>Hi</title><link rel="apple-icon-touch-precomposed" href="icon.jpg" /></head><body></body></html>';
alert($(theHTML).filter('link[rel="apple-icon-touch-precomposed"]').attr('href'));
JSFiddle Demo
I'm not sure if you can use .find that way, I'd have to read the API about it. But, you can try .prop('href') instead of .attr('href'). If that doesn't work, I'd also suggest using an * after the = like link[rel=*"apple-icon-touch-precomposed"]

Can JQuery and Javascript be mixed together?

I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}

Categories

Resources