var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{
(function(i){
g.children[i].onclick = function(){
$('.galao')[i].attr('id','selectedGalao');
}
})(i);
};
So, I'm trying to get a element by his class and index position so I can add an id that I work with. The problem is the browser returns me:
Uncaught TypeError: Cannot read property 'attr' of undefined at HTMLDivElement.g.children.(anonymous function).onclick
How do I fix it?
EDIT
The code is actually like this:
var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{
(function(index){
g.children[i].onclick = function(){
$('.galao')[index].attr('id','selectedGalao');
}
})(i);
};
This way:
var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{
(function(){
g.children[i].onclick = function(){
$($('.galao')[i]).attr('id','selectedGalao');
}
})(i);
};
The elements inside a jquery array, aren't jquery objects, so you need to make them jquery objects too, to use jquery functions on them
If you are using jQuery, use it properly, it will optimize your code great deal:
$('#my_div').children().click(function() {
$('.galao').eq(i).addClass('selectedGalao');
})
Another advice, use class selectedGalao, not id, as id must be unique, and if multiple elements can get same selectedGalao id, this is not right.
Try something like this:
var g = $('#my_div');
for (var i = 0; i < g.children.length; i++) {
g.children()[i].on('click', function () {
$('.galao')[i].attr('id','selectedGalao');
});
};
Related
This question already has answers here:
$.each() vs for() loop - and performance
(6 answers)
Closed 5 years ago.
I want to replace my
$("p").each(function(i)
with
for (var i = 0, len = $('p').length; i < len; i++) {
$('p')[i];
}
for faster performance. I want to keep the same switch statement. How do i do it? I'm new with javascript and also my switch statement is alot longer , but i shorten it so you guys can see it better. My problem is $(this) . Thanks in advance.
for (var i = 0, len = $("p").length; i < len; i++) {
$("p")[i];
}
$("p").each(function(i) {
switch(window.localStorage['kgenfavred' + i])
{
case 'yred':
$(this).addClass("favoritesred");
$(this).removeClass("favoritesyellow");
break;
}
});
var paragraphs = document.getElementsByTagName('p');
for (var p = 0; p < paragraphs.length; p++) {
switch(window.localStorage['kgenfavred' + p]) {
case 'yred':
paragraphs[p].classList.add('favoritesred');
paragraphs[p].classList.remove('favoritesyellow');
break;
}
}
JSFiddle example
Your current approach is likely to be slower, since you've added a DOM lookup on each iteration. If you really want to convert to a for loop, capture your element set first, then iterate over it - accessing the current element with .eq(index):
var $p = $('p');
for (var i = 0, len = $p.length; i < len; i++) {
// get jquery element
console.log($p.eq(i));
// or get DOM node
console.log($p.get(i));
}
As #Kinduser pointed out, it probably would be fastest/easiest just to cut jQuery out of the picture altogether:
var p = document.querySelectorAll('p');
for (var i = 0; i < p.length; i++) {
console.log(p[i]);
}
Or newer:
document.querySelectorAll('p').forEach((element) => {
console.log(element);
});
This would be incorrect. You can use .each() method of jQuery:
var $ps = $(document).find('p');
for (var i=0; i<$ps.length; i++)
{
let temp = $ps[i]; /// this is a dom element and if you want use jQuery methods, you need to use a selector over it;
let $temp = $(temp); /// this is jQuery element
/// Do whatever you want here
}
Here is my code snippet
for (var k = 0; k < link_list.length; k++) {
var service_list = document.getElementsByName("service_info");
service_list = $(service_list).children("div[name=service_info_element]");
for (var i = 0; i < service_list.length; i++){
var service_info = {};
service_info["service_name"] = $(service_list[i]).find("select[name=service_name]").val();
service_info["service_type"] = $(service_list[i]).find("input[name=service_type]").val();
}
How can I get $(service_list[i]).find("select[name=service_name]").val() and $(service_list[i]).find("input[name=service_type]").val(); for each link_list[k] inside the second loop. I mean I need something like link_list[k].service_list[i].find("select[name=service_name]").val()
You can try this it'll work
$('service_list[i]').find('select[name=service_name]').filter([0,3,4]).anything();
Try the following:
link_list[k].service_list[i].find("select[name=service_name]").each(function(i, element){
var val = $(this).val(); // or element.val()
});
I have a set of variables:
var var1 = 0;
var var2 = 0;
var var3 = 0;
var var4 = 0;
var var5 = 0;
And I want to check them all with a for Loop, but I'm not quite sure of the syntax:
for( var i = 1; i<6; i++){
alert(var[i]);
}
that for loop yields no results.
Put them in an array instead.
var vars = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < vars.length; i++) {
alert(vars[i]);
}
If you're defining the varables in the global scope, you can access the values using window['var'+i]:
for(var i = 1; i<6; i++){
alert(window['var'+i]);
}
To access them you would have to use the scope to which they were written. If your code is in the window scope that would then become:
for( var i = 1; i<6; i++){
alert(window['var'+i]);
}
Though of course it's far cleaner if it's in a different scope specific to whatever you're doing. In those cases often
for( var i = 1; i<6; i++){
alert(this['var'+i]);
}
would work.
The data construct you are using is not good for this. Using an array or object is much more feasible for what you want to do as well as being easily extendable.
var arr = [0,0,0,0,0,0];
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
var[i] is used it var is an array. But in your case it isn't. The best way would be to place those values in an array, like;
var myvar = [0,0,0,0,0];
then use the for loop to check for the value.
for( var i = 1;i<6; i++){
alert(myvar[i-1]);
}
How do I get the value of BrandID?
Use this yourObjectArray[0].Item.BrandID
For your example:
objRef[0]["Item"]["BrandID"]
or you can use:
objRef[0].Item.BrandID
For Iterating in your array you will use:
var i;
for(i=0; i < objRef.Length ; i++)
{
var brandId = objRef[i].Item.BrandID;
// or
var brandId = objRef[i]["Item"]["BrandID"];
// your code blocks to process blockId
}
Go with this ..
ObjectArray[0].Item.BrandID
You mean this?
for(var i = 0, len = yourObjectArray.length; i < len; i++) {
var youNeed = yourObjectArray[i].Item.BrandID;
}
This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.