How to replace .each() with for loop in javascript [duplicate] - javascript

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
}

Related

How to remove all elements except last one with same document.querySelectorAll(".someClass") using only javascript without jQuery

My query is simple :
How to remove all elements except last one with same document.querySelectorAll(".someClass") using only javascript without jQuery.
I can do it with jQuery with only one line like this:
$('.someClass').not(':last(2)').remove();
But I want to do it with pure JavaScript; how can I do that?
Any idea?
I tried this code :
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
But it removes all elements except the first one. But I want to keep the last one.
This will remove all but the last element from your nodeList
EDIT:
const elems = Array.from(document.querySelectorAll(".someClass"))
elems.pop()
elems.map(node => node.parentNode.removeChild(node))
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length -1; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Try using this.
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
if (i !== lists.length - 1) lists[i].parentElement.removeChild(lists[i]);
}
You can perform the above action on every item in the array except for the last one (the last index is array.length - 1 since the first index is 0.
You were close:
let endIndex = 1 // how many you want to delete
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length - 1 - endIndex; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Stop just before the last one:
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length - 1; i++) {
// ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
lists[i].parentElement.removeChild(lists[i]);
}
Or alternatively, in all vaguely-modern browsers:
const lists = Array.prototype.slice.call(
document.querySelectorAll(".someClass"),
0, -1
);
for (const list of lists) {
list.remove();
}
That uses the slice method from Array.prototype to grab all of the entries from the NodeList returned by querySelectorAll except the last one, then loops over that result removing those elements.
Try with this:
$("#parent_id").children(":not(#id_n)").remove();

how to remove a dom element with javascript? [duplicate]

This question already has answers here:
Removing HTMLCollection elements from the DOM
(5 answers)
Closed 8 years ago.
i have a link and i would like to remove it using javascript
here's what i have so far
test
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; ++i) {
if (a[i].innerText === 'test') {
a.remove();
}
}
this will fail.
Don't do it this way. document.getElementsByTagName('a') returns live collection, so loop in reverse order. So try
var aColl = document.getElementsByTagName('a');
for (var i = aColl.length-1; i >= 0; i--) { //loop from reverese order, so that removed item doesn't affect
var thisNode = aColl[i];
if (thisNode.innerHTML === 'test') {
thisNode.parentNode.removeChild(thisNode );
}
}
Fiddle
If you do it for (var i = 0, len = a.length; i < len; i++) { then you end up removing only half of it, since each removal will update the NodeCollection in a and you will end up losing the elements at higher index and your check will fail.

Remove elements whose id name contains certain string

I want to remove all elements (suppose they're all divs) whose id name contains the string bs. How to do this via javascript regardless of they are nested elements or not? (not jquery)
<div id="new_bs_add"></div>
<div id="bsremove"></div>
<div id="somethingelse"></div>
... and many more
No jQuery, but if there's support for CSS3 selectors you can go for
var rem = document.querySelectorAll("[id*='bs']"), i = 0;
for (; i < rem.length; i++)
rem[i].parentNode.removeChild(rem[i]);
Otherwise, just go for this slight edit of VisioN's solution:
var divs = document.querySelectorAll("[id]");
for (var i = 0, len = divs.length; i < len; i++) {
var div = divs[i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
Pure JavaScript:
var divs = document.getElementsByTagName("div");
for (var i = divs.length; i;) {
var div = divs[--i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
As an example, in jQuery it is one line:
$("div[id*='bs']").remove();
DEMO: http://jsfiddle.net/c4ewU/
The most portable method to obtain a list of elements is document.getElementsByTagName. However the resulting list is a live node list which means that if you modify the document, the list changes too!
There are two solutions for this. One is to take a copy of the list:
var nodes = document.getElementsByTagName('div');
var copy = [].slice.call(nodes, 0); // take a copy
for (var i = 0, n = copy.length; i < n; ++i) {
var d = copy[i];
if (d.parentNode && d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
}
}
The second is to either work through the list backwards, or ensure that you don't advance the iterator if you modify the list. This takes the latter approach:
var nodes = document.getElementsByTagName('div');
for (var i = 0; i < nodes.length; /* blank */ ) {
var d = nodes[i];
if (d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
} else {
++i; // iterate forward
}
}
try this code
first get all elements contain certain text (here 'bs')
var matches = [];
var searchElements = document.getElementsByTagName("body")[0].children;
for(var i = 0; i < searchElements.length; i++) {
if(searchElements[i].tagName == 'DIV') {
if(searchElements[i].id.indexOf('bs') != -1) {
matches.push(searchElements[i]);
}
}
}
Then delete them from body of html
for(var i = 0;i<matches.length; i++)
matches[i].parentNode.removeChild(matches[i]);
If you remove them in the first loop, there will be some tags will not deleted as the children array length is decreased each time you delete a node. So the better way to get them all in an external array and then delete them.

Javascript for loop until - multiple conditions

I am using javascript, using regex to scrape images from html code.
I want the loop to run either until the script finds no more images or until it reaches 12.
I'm trying the following but not working:
var imgs = d.getElementsByTagName('img'), found = [];
for(var i=0,img; ((img = imgs[i]) || ( $i < 13)); i++)
Is this possible? Am I on the right lines?
Quite new to javascript but trying!
You should use && instead of ||. Also, $i should be i.
for(var i=0, img; (img = imgs[i]) && (i < 12); i++)
found.push(img);
Assuming that you want found to contain those first 12:
var imgs = d.getElementsByTagName('img');
var found = [].slice.call(imgs, 0, 12);
You have to use [].slice.call(imgs, ...) instead of imgs.slice() because imgs is only a pseudo-array, and not a real array.
An alternative to writing [].slice is Array.prototype.slice.
If you want to do something else inside the loop, just use the array created above to ensure that you only work on the first 12 images:
for (var i = 0, n = found.length; i < n; ++i) {
// do something with found[i];
}
I personally hate when people do assignment in the condition clause of a for loop, since it looks like someone mistook an assignment (=) for a comparison (=== or ==). Better to do the logic elsewhere.
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length,
max = imgsLength > 13 ? 13 : imgsLength;
for (i = 0; i < max; i++) {
found.push(imgs[i]);
}
or
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length;
for (i = 0; i < 13 && i < imgsLength; i++) {
found.push(imgs[i]);
}
For Loop with multiple statements
let products= [...]
let users= [...]
for(let i=0,userParam = null, productParam=null; i<products.length; i++, userParam=products[i], productParam=products[i]){
....
}

Compare arrays with jQuery [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Simplest code for array intersection in javascript
How to merge two arrays in Javascript
There are three arrays:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_new = Array();
First one is general, second is the items currenly in use. Third one includes all the items from the first array, witch are not mentioned in second.
How do I remove from the first array items, witch are used in second, and write the result to the third array?
We should get items_new = Array(523, 334, 5346). 3452 and 31 are removed, because they are mentioned in second array.
You could do this:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_compared = Array();
$.each(items, function(i, val){
if($.inArray(val, items_used) < 0)
items_compared.push(val);
});
That's it
Why not a simple for loop?
for(var j = 0; j < items.length; j++)
{
var found = false;
for(var k = 0; k < items_used.length; k++)
{
if(items_used[k] == items[j])
{
found = true;
break;
}
}
if(!found)
items_compared.push(items[j]);
}
As a faster solution maybe :
var j, itemsHash = {};
for (j = 0; j < items.length; j++) {
itemsHash[items[j]] = true;
}
for (j = 0; j < itemsUsed.length; j++) {
itemsHash[itemsUsed[j]] = false;
}
for (j in itemsHash) {
if (itemsHash[j]) {
itemsCompared.push(j);
}
}
runs in O(n) time, with a little more memory.
Basically I would make the third have all elements in the first, then loop through the second array removing all of those elements found in the first.
var items_compared = items;
for(int i = 0; i < items_used.length; ++i)
{
var indx = $.inArray(items_used[i], items_compared);
if(indx != -1)
items_compared.splice(indx, 1);
}

Categories

Resources