getElementsByClassName vs. jquery - javascript

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

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

JavaScript vs jQuery Selector

I was wondering what the difference between jQuery selectors $("#fake-div) and JavaScript selectors getElementById("fake-div"). First, are these even called JavaScript selectors?. I know jQuery returns the jQuery object whereas JavaScript selectors returns the DOM element; however, given these two blocks of code:
jQuery Selector
var post = $("#postid");
var reply_list = post.find(".replies_ul");
var current_reply = document.createElement("li");
current_reply.setAttribute("class", "reply_li");
reply_list.insertBefore(current_reply, reply_list.firstChild);
JS Selector
var content_list = document.getElementById("content_ul");
var current_post = document.createElement("li");
current_post.setAttribute("class","content_li");
content_list.insertBefore(current_post, content_list.firstChild);
The jQuery Selector ends up removing the list from the DOM when the last line of code is called, and the JavaScript selector successfully inserts the list item at the top of the list. I'm looking for an explanation as to what is going on.
The jQuery insertBefore in your code is invalid, it takes two arguments whereas the jQuery accepts only one:
.insertBefore( target )
Description: Insert every element in the set of matched elements before the target.
And the normal one:
Node.insertBefore
Description: Inserts the specified node before a reference element as a child of the current node.
parentElement.insertBefore(newElement, referenceElement)
The difference is not on the selector but on the method / function that you are calling.
You are using the jQuery insertBefore function and comparing it with the javascript insertBefore function.
In jQuery the insertBefore function has only one parameter and therefore you are using it wrong.
If you want to make use of the Javascript function insertBefore instead of the jQuery one, then you have to convert your jQuery object reply_list to a Javascript one.
You can do this by using .get(0) or [0] like so:
reply_list[0].insertBefore(current_post, content_list.firstChild);
//or like this
reply_list.get(0).insertBefore(current_post, content_list.firstChild);
In your first block of code, the reply_list is a jQuery object; meaning it doesn't actually have a .firstChild property.
Change it to this:
reply_list.get(0).insertBefore(current_reply, reply_list.get(0).firstChild);
Please note the differences between jQuery's insertBefore and JavaScript's insertBefore

List of li elements in jquery

I don't know why my code doesn't work.
$("#example").find('LI A').hasClass("sth").each(function(){alert($(this))});
Firebug says:
$("#example").find('LI A').hasClass("sth").each is not a function
The problem in this code is each, because if I delete it, it giving me no errors.
I need to pass founded value of "a" element to array.
hasClass function returns boolean not a jQuery object. thus it doesn't have the each function.
You probably meant this:
$("#example").find('LI A.sth').each(function(){alert($(this))});
Or this (which is better):
$("#example li a.sth").each(function(){alert($(this))});
Read the docs:
.hasClass( className ) Returns: Boolean
Description: Determine whether any of the matched elements are assigned the given class
Your application of hasClass is incorrect. It does not return a jQuery Object, but a boolean, so .each() cannot be applied to it.
You have to attach the class to the selector
$("#find").click(function (){
$("#example").find('a.sth').each(function(){
$("#test").append($(this));
});
});
Demo

Difference between $('div div') and $('div').find('div')?

I was just poking around with jQuery, and I stumbled upon the Find function.
I tested like this:
$(document).ready(function(){
$('button').click(function(){
$('div').find('div').fadeOut(2000);
});
});
And this
$(document).ready(function(){
$('button').click(function(){
$('div div').fadeOut(2000);
});
});
And both produce the exact same result.
Whats the difference? :)
In your example there is no difference but there are cases that you can not use the first one, for example let't say you have an element as the parameter of a function and you want to find divs inside it, then you have to use the "Find" method.
function foo(index, el)
{
$(el).find("div")...
}
But when you know the exact path, obviously the second approach is more robus.
There is no difference.
If you already have a jQuery object, the find method is useful.
Otherwise, a single selector is simpler.
Most selectors have method equivalents (.children(), .first(), .not()) for this reason.
The method versions also allow you to call .end() to go back to the previous object.
They both do exactly the same thing, but in older browsers where document.querySelectorAll() is not available (Old IEs) $("div").find("div"); is quicker, as Paul Irish confirms in this comment here.
Another thing to note is that in jQuery you can also do this:
$("div", "#some-element")
Which would search for div inside of #some-element. jQuery actually converts this into:
$("#some-element").find("div")
So it's always suggested to use .find() rather than pass in a context.
In this specific case, they do the same thing. Note that find() will traverse all the descendants of the matched elements.

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