List of li elements in jquery - javascript

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

Related

findpos work on ID but not class in javascript

highlightedBlock = document.getElementById("post-" + getLinkID);
console.log(findPos(highlightedBlock));
console.log(findPos($('.bar-holder')));
my second console.log return NAN, and I tried many different classes. Is this normal?
Looks like it is looking for a dom element reference(from the parameter sent to first call)
The jQuery method returns a jQuery wrapper object, not a dom element reference that could be the reason for the said result.
console.log(findPos(highlightedBlock));
console.log(findPos($('.bar-holder')[0]));
If you have multiple elements with the said class, then you will have to iterate through each element and then call findPos for each of them
$('.bar-holder').each(function () {
console.log(findPos(this))
})

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

Working with jQuery Collections

I'm trying to increase my understanding of jQuery. Please consider the following code.
if ($('.myClass').data('id') == '123') {
}
How does this work? It looks simple enough until you understand that $() returns a collection of elements. So what does the code above do exactly? How does it make sense to compare the value of the data-id attribute for a collection of elements like this?
(I understand I can use each() to explicitly test each element in the collection. My question is about what the code above does.)
.data('id') returns the value for the first item in the collection, but .data('id','xyz') will set the value for all items in the collection - much the same behaviour as other jQuery methods like .html(), .text(), etc.
It may not seem to make sense to just test the first in an if statement like that, but it makes more sense for cases where you know there will be exactly one element, for example when your selector is an id, or when you use $(this).data('id') inside an event handler or something.
If you are asking how to test whether all items in the collection have a particular data value you can do this:
var $col = $('.myClass');
if ($col.length === $col.filter(function(){return $(this).data('id') === '123';}).length) {
// do something
}
Or if you just want to know if at least one has that data value:
if ($('.myClass').filter(function(){return $(this).data('id') === '123';}).length > 0) {
// do something
}
I believe if you're trying to get a value through a jquery function, it returns the value from the first item in the collection. for example if you have:
<div class='1'></div>
<div class='2'></div>
<div class='3'></div>
and you run:
$('div').attr('class');
it will return "1". I don't know if this is uniform through all jQuery functions, but this is the expected behavior.
You can use jQuery .each() - http://api.jquery.com/jQuery.each/
Example in comments since stackoverflow doesn't like jsFiddle that much.

What does the second argument to $() mean?

I have a jQuery code as follows;
var favorites = $("#favorites");
var favoritesFooter = $("#favoritesFooter",favorites);
I am not sure what does the comma mean in the 2nd statement $("#favoritesFooter",favorites);
Also what would the following statement do or represent in the above case;
favoritesFooter.prev().after(newHTML);
It's the second parameter to $(). As explained in the documentation:
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$('div.foo').click(function() {
$('span', this).addClass('bar');
});
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
The second statement means "search for element with ID of favoritesFooter inside the jQuery object favorites".
As you're dealing with ID which should be unique, it's pointless - $("#favoritesFooter") is the best practice.
Regarding favoritesFooter.prev() it's also pointless, assuming the ID is unique so you have collection with only one element thus prev() will return empty jQuery collection.
The .prev() will take the previous DOM element - in your case, it will push newHTML right before the favoritesFooter element.

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources