Im trying to give the last created class a number, I know that in Jquery i could use :last but how is it in JavaScript ?
I have tried a loop but it does not really do it ? Any suggestions ?
This is what i have for now.
var x=document.getElementsByClassName("sticker");
for (var i = 0; i<x.length; i++){
x.innerHTML=Math.floor((Math.random()*1000000)+1);
<div class="sticker"></div>
<div class="sticker"></div>
<div class="sticker">155477</div>
I'm not sure that i fully understood what you mean but i think that you want the following:
var x=document.getElementsByClassName("sticker");
x[x.length-1].innerHTML=Math.floor((Math.random()*1000000)+1);
Try
var x=document.getElementsByClassName("sticker");
x[x.length - 1].innerHTML=Math.floor((Math.random()*1000000)+1);
You can just get the last element in the collection by using the length for index computation:
var x = document.getElementsByClassName("sticker");
if (x.length)
x[x.length-1].innerHTML = Math.floor((Math.random()*1000000)+1);
Simply check for the last iteration of your loop:
for (var i = 0; i < x.length; i++){
if (i == x.length - 1) {
x[i].className = x[i].className + " newclass";
}
}
Related
I'm trying to get some informations from the page.
If there is one entry I can do that by
var z = document.querySelector('div.class').innerText;
and then get it by +z somewhere where I need the value.
But if there are more entries it will get only first.
I'm trying to do sth like that to get them all:
var x = document.querySelectorAll('div.class');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
But definitely something's wrong with this code. I'm not really familiar with JS, could you help me how to get all entries?
You can achieve that by using getElementsByClassName('class').
The script would be sort of:
let list = document.getElementsByClassName('class');
for (let i = 0; i < list.length; i++) {
console.log(list[i].innerText);
}
https://jsfiddle.net/esjcaqwb/
Your code looks ok, heres a working example that might be useful.
var x = document.querySelectorAll('.example');
var r = document.querySelectorAll('.result')
var i;
for (i = 0; i < x.length; i++) {
r.innerText += x[i].innerText;
}
What was going wrong with your code? In the example you provided, you're getting the value but not doing anything with it.
With your actual code you are not doing anything in the loop, the statement x[i].innerText; does nothing.
If you want to get these elements contents in an array you can use:
var results = Array.from(x).forEach(function(el){
return el.innerText;
});
I've never worked with prototype, and maybe I don't even understand how it works, so here I am.
I'm trying to change how .push() works in javascript: it adds the parameter as the last element, but I want it to add the parameter in the first position.
Here is my non-working guess:
Array.prototype.push() = function(e){
var x = [e];
return x.concat(this);
}
Sorry for the breathtaking mistakes I probably made :)
Disclaimer: I'm just trying to understand how to modify native methods. Why is everybody so scared?
Just loose the parenthesis :
Array.prototype.push = function(e){
var x = [e];
this.unshift(e);
}
EDIT:
If you don't want to use unshift inside, you can do splice :
Array.prototype.push = function(e){
var x = [e];
var y = [];
for(var j = 0; j< this.length; j++) y[j] = this[j];
this[0] = x;
for(var i = 0; i < y.length; i++) this[i+1] = y[i];
}
To add element in first position use .unshift. You don't need prototype for this.
You don't want to override .push() or any other native method.
var data = [1,2,3,4,5];
data.unshift(10);
// 10 is first element
console.log(data);
In JavaScript, for a array, if methods such as pop, shift is used, the length of array changes as well. In my JS code below, it never executes the third elements 'Ds3' in the array since after the notes.shift() is executed, the length of the array becomes 0 so it just jumps out of the for loop, I do not know how to change the code so it can actually execute the 'Ds3'. Hope someone could help me out. Thank you in advance.
Code 1:
$(document).ready(function() {
var notes = ['F2', 'As2','Ds3'];
for(i = 0; i < notes.length; i++) {
$('#_' + notes.shift()).addClass('just_do_it');
alert(notes.length);
}
});
For code 2, I do not know why when I sort of make the one line code to two liner, the code does not work at all. Thank you in advance.
code 2:
$(document).ready(function() {
var notes = ['F2', 'As2','Ds3'];
var count = 0;
for(i = 0; i < notes.length; i++) {
var note = notes.shift();
$('#_' + note).addClass('just_do_it');
count++;
alert(notes.length);
}
});
Is there a reason why you want to empty that array? If insist on it, try changing to a while loop.
var notes = ['F2', 'As2','Ds3'];
var count = 0;
while(notes.length > 0){
var note = notes.shift();
$('#_' + note).addClass('shown');
count++;
alert(notes.length);
}
If I may add, you're also incrementing the count as you loop through the array. Rather you can get the count immediately just by getting the length of the array like this var count = notes.length
Also since you mentioned pop and shift arrays methods, you should checkout other array methods such as forEach, map or reduce
Since shift() is indeed destructive you could simply use the index of that iteration in the loop and leave the array unaltered
for(i = 0; i < notes.length; i++) {
// switch from `notes.shift() to notes[i]
$('#_' + notes[i]).addClass('just_do_it');
count++;
alert(notes.length);// length remains unchanged
}
Or using join() to create a selector for all and not use any loop
$('#_' + notes.join(',#_') ).addClass('just_do_it');
You could also try:
for (var count = notes.length; count > 0; count--) {
$('#_' + notes.shift()).addClass('just_do_it');
}
or
while (notes.length > 0) {
$('#_' + notes.shift()).addClass('just_do_it');
}
I want to build a list. No problem.
for (i = 0; i < 7; i++) {
$('#domid').append(variable.clone());
}
How do I get the LAST item in the list (in this case i.7) and add a class to it?
for (i = 0; i < 7; i++) {
$('#domid').append(variable.clone());
if (i===7) {
$('.domclass').addClass('last');
};
}
But that won't work. That just makes all of the .todo items have the class when the counter get's to 7.
Any suggestions on how to find this?
Thanks!
$('.domclass:last').addClass('last');
Or, if you'd like to do it in the loop (so, as the commenter pointed out, you don't have to traverse the DOM to get to the element again):
var newElement;
for(var i = 0; i < 7; i++){
newElement = variable.clone();
$('#domid').append(newElement);
if(i === 6) {
$(newElement).addClass('last');
}
}
i never equals 7 because the loop runs while i < 7
eq() with a negative index count backward.
$('.domclass:eq(-1)');
http://api.jquery.com/eq/
One way to do it is within the loop store a reference to the cloned item:
var i,
$item,
$domid = $('#domid');
for (i = 0; i < 7; i++) {
$item = variable.clone();
$domid.append($item);
}
$item.addClass('last');
When the loop ends $item will be the last one added. Of course this assumes the loop will always run for at least one iteration - if the number of iterations is variable and might be zero you could say:
if ($item) $item.addClass('last');
(Note that I'm also storing a reference to the #domid element rather than reselecting it on every iteration.)
This his how I would do it:
var $domid = $( '#domid' );
for ( var i = 0; i < 7; i+= 1 ) {
$domid.append( variable.clone() );
}
$domid.children( ':last' ).addClass( 'last' );
How do I get access to live DOM collections from jQuery?
Take for example this HTML <div id='a'></div> and this JavaScript code:
var a = $('#a');
var divs = a[0].getElementsByTagName('DIV');
for(var i=0; divs.length < 20; ) {
a.append($('<div>'+(i++)+'</div>'));
}
It will append 20 div children to <div id='a'> because divs is a live collection.
Is there anything in jQuery that I could replace the second line with to get the same result?
var divs = $('#a div'); results in infinite loop.
JSFiddle is here.
In case #a already contains divs:
var $a = $('#a'),
toAdd = Math.max(20 - $a.find('div').length, 0);
for (var i = 0; i < toAdd; i++) {
$a.append('<div>' + i + '</div>');
}
That would be equivalent to the code above.
Live Collections - the true ones, are not something which can be returned by modern jquery.
Moreover, modern method which is intended to replace in nearest future getElementsByTagName, getQuerySelectorAll also return a static collection.
This is the answer to question you've stated.
As for the question you've really wanted to ask, other users already tried to provide you some help.
Select the element each time, this will create a new jQuery object. Which I think it the only way if the element is changing.
var a = $('#a');
for(var i=0; $('#a div').length < 20; ) {
a.append($('<div>'+(i++)+'</div>'));
if(i==50) break;
}
EDIT:
Or this:
for(var i=0, a=$('#a'); a.children('div').length < 20; ) {
a.append($('<div>'+(i++)+'</div>'));
if(i==50) break;
}
Or this, just one selector:
var a = $('#a');
var length = a.children('div').length;
while(length < 20) {
a.append($('<div>'+(length++)+'</div>'));
}
How to get DOM live collections with jQuery?
That’s not possible.
This has the same effect as your example code, though:
var $a = $('#a');
for (var i = 0; i < 20; i++) {
$a.append('<div>' + i + '</div>');
}
http://jsfiddle.net/mathias/Af538/
Update: If the code needs to be repeated periodically, you could use something like this:
var $a = $('#a'),
toAdd = Math.max(20 - $('div', $a).length, 0),
i;
for (i = 0; i < toAdd; i++) {
$a.append('<div>' + i + '</div>');
}
http://jsfiddle.net/mathias/S5C6n/
Is it always 20 div children ?
Isn't it better to use the following
var a = $('#a div');
for(var i=0; i < 20; i++) {
a.append($('<div>'+(i)+'</div>'));
}
The syntax you're looking for is:
var divs = $('div#a');
Since IDs are supposed to be unique, you could just do:
var divs = $('#a');