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

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()

Related

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

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

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 :)

getElementsByClassName vs. jquery

If my original function was:
document.getElementsByClassName('blah')[9].innerHTML = 'blah';
...how would I change that so I get that same item in jquery? I have this, but when I put '[9]' at the end it doesnt work:
$(data).find('.blah')[9].html();
It I leave the [9] out, it only gets the first item whose class name is 'blah', and I want it to get the 10th item.
The equivalent of
document.getElementsByClassName('blah')[9].innerHTML = 'blah';
is to use the :eq pseudo-selector:
$(".blah:eq(9)").html('blah');
or the eq function:
$(".blah").eq(9).html('blah');
(...and then the html function to set the inner HTML.)
See what you are looking for is :eq():
$('.blah').eq(9).html('blah');
because :eq() is 0 indexed,so :eq(9) will find the item at 10th index.
.eq() jQuery doc
There is :nth-child() function too:
$('.blah:nth-child(10)').html('blah');
because :nth-child() is 1 indexed so you have to give place 10th position there.
:nth-child() jQuery doc
from the docs:
Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as :eq() or :even jQuery follows JavaScript's "0-indexed" counting. Given a single containing two s, $('li:nth-child(1)') selects the first while $('li:eq(1)') selects the second.
try the following
$('.blah').eq(9).html('blah');
Try this
$('.blah').eq(9).html('blah');
You should also just be able to use jQuery's get() method:
$('.blah').get(9)
jQuery objects also function as indexed arrays as returned elements, so this should also work:
$('.blah')[9]
Another answer could be:
$($(data).find('.blah')[9]).html();
When you use [9] it returns a DOM object which doesn't know what function html() is but without [9] it returns a jQuery Object which the html() function is apart of.
Try this
$(".blah:eq(9)").html('blah');
$('.blah')[9].innerHTML="BLAH";
This should solve your problem

Using jQuery what's the way to get all elements of a queried set EXCEPT the first.

Using jQuery what's the way to get all elements of a queried set EXCEPT the first. I forget offhand.
You can do:
$(selector).not(':first');
Or:
$('selector:not(:first)');
I believe you are refering to the NOT selector .
$("div.someClass:not(div.someClass:first)")
Assuming of course you are looking for div.someClass. This might be a bit verbose, but I think it works. Haven't tested.
Another option is the gt selector (greater than):
$('selector:gt(0)');
or
$('selector').gt(0);
:not(:first) is more readable, but also a bit longer.
You could also use the splice method, e.g.
var nodes = $(selector);
nodes.splice(0, 1);

Prototype get by tag function

How do I get an element or element list by it's tag name. Take for example that I want all elements from <h1></h1>.
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
document.getElementsByTagName('a') returns an array. Look here for more information: http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName
Amendment: If you want a real array, you should use something like Array.from(document.getElementsByTagName('a')), or these days you'd probably want Array.from(document.querySelectorAll('a')). Maybe polyfill Array.from() if your browser does not support it yet. I can recommend https://polyfill.io/v2/docs/ very much (not affiliated in any way)
Use $$() and pass in a CSS selector.
Read the Prototype API documentation for $$()
This gives you more power beyond just tag names. You can select by class, parent/child relationships, etc. It supports more CSS selectors than the common browser can be expected to.
Matthias Kestenholz:
getElementsByTagName returns a NodeList object, which is array-like but is not an array, it's a live list.
var test = document.getElementsByTagName('a');
alert(test.length); // n
document.body.appendChild(document.createElement('a'));
alert(test.length); // n + 1
You could also use $$(tag-name)[n] to get specific element from the collection.
If you use getElementsByTagName, you'll need to wrap it in $A() to return an Array. However, you can simply do $$('a') as nertzy suggested.

Categories

Resources