0

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;
      }
   });
KiRa
  • 924
  • 3
  • 17
  • 42
Havenht
  • 3
  • 3
  • Would calling `jQuery()` at each iteration decrease time of procedure? Why is jQuery necessary to iterate `

    ` elements? What is performance benchmark for current approach?

    – guest271314 Mar 13 '17 at 21:57
  • I read in other articles that its does. https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead and http://stackoverflow.com/questions/11887450/each-vs-for-loop-and-performance – Havenht Mar 13 '17 at 22:00
  • The linked Answers list the performance for using jQuery and not using jQuery. How is current Question different from linked Question? – guest271314 Mar 13 '17 at 22:02
  • its a lot longer code than what i have here, but that is what i need. I just need to replace each() with for loop. how do i do it?. and thanks again for your replied. – Havenht Mar 13 '17 at 22:02
  • i want to replace each() with for loop and have the same switch statement with $(this) , so it should look like somthing like this for (var i = 0, len = $("p").length; i < len; i++) { $("p")[i]; switch(window.localStorage['kgenfavred' + i]) { case 'yred': $(this).addClass("favoritesred"); $(this).removeClass("favoritesyellow"); break; }} – Havenht Mar 13 '17 at 22:05
  • Use answers at linked Question. – guest271314 Mar 13 '17 at 22:05
  • 1
    If you want better performance, just stop using jQuery. Otherwise, you're just kidding yourself. –  Mar 13 '17 at 22:05

3 Answers3

2
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

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Klemen Tusar
  • 9,261
  • 4
  • 31
  • 28
  • 1
    Does calling `jQuery()` within `switch()` decrease total time of procedure? – guest271314 Mar 13 '17 at 22:03
  • Don't use `for-in` on an Array-like object. It causes problems, and is generally shown to be slower than a `for` anyway, especially with the `.hasOwnProperty()` check. –  Mar 13 '17 at 22:07
  • Cool!!! that work!!!! – Havenht Mar 13 '17 at 22:12
  • hey sorry, i meant to give you a 1 point up, but accidently click -1, and now i don't know how to change it lol I new with this site and this is my first post.thanks alot, your code work :) – Havenht Mar 13 '17 at 22:19
  • LOL :D Well, click back up so it gets 0. :D – Klemen Tusar Mar 13 '17 at 22:21
  • 1
    @squint Thanx for the info. Will keep that in mind. Edited the snippet and JSFiddle above. – Klemen Tusar Mar 13 '17 at 22:25
  • One more... `paragraphs[p].className += ' favoritesred';` should use `.classList` like the line below it so that it can't add the same class twice. `paragraphs[p].classList.add("favoritesred")` –  Mar 13 '17 at 22:26
  • Noted & fixed. :) – Klemen Tusar Mar 13 '17 at 22:32
1

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);
});
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Does calling `.eq()` at each iteration decrease total time of procedure? – guest271314 Mar 13 '17 at 21:58
  • 1
    Wouldn't be it better to just get rid of the whole jQuery? Not only the `each()` function. – kind user Mar 13 '17 at 21:59
  • @Kinduser probably yes... @guest27314 It's not the `.eq` part that is faster, it is the fact that you are getting an element at index `i` of an *existing collection* of DOM nodes (`$p`) rather than creating the collection on each iteration and accessing index `i` – Rob M. Mar 13 '17 at 22:01
  • @RobM. `.eq()` is a function call that is not necessary to achieve expected result described at OP "for faster performance." – guest271314 Mar 13 '17 at 22:04
  • @guest271314 if you want the jQuery node at the given index, it is useful - perhaps not 100% necessary – Rob M. Mar 13 '17 at 22:05
  • 1
    @RobM. You can substitute bracket notation for `.eq()` function call to get `DOM` element, if _"for faster performance"_ is requirement – guest271314 Mar 13 '17 at 22:08
  • WOW you guys are great!! techouse code got it working, but i'll look thru all of your advices and code and try to make my code better , thanks alot !! – Havenht Mar 13 '17 at 22:14
0

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
  }
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17