Hey gang, in this JavaScript tutorial I just wanted to show you a quick practical example of using loops to change elements on a HTML page. In this example, we’ll create an array of all the anchor tags on our HTML document, cycle through them using a for loop, and then add a dynamic class name to them dependant on their position in the page/array.

As always, fire away with any questions you have ninjas :).


========== JavaScript for Beginners Playlist ==========

========== CSS for Beginners Playlist ==========

========== HTML for Beginners Playlist ==========

========== The Net Ninja ============

For more front-end development tutorials & to black-belt your coding skills, head over to – or

========== Social Links ==========

Twitter – @TheNetNinja –


  1. links[i].className = "link-" + i;
    why this line shows error saying 'cannot set className' of undefined..
    please help me fast n correct me if I'm doing something wrong

  2. So is this JS actually changing the content of the HTML file? If you were wanting to do this quickly for a huge HTML file with 10000 links, it's only changing the class in the console, but the actual HTML file is the same as before, right?

  3. can I use a loop to download images from a webpage. for example, if i ooened the console and created a loop can i have that loop target all of the image elements on that page and download them to my desktop?

  4. Same code as yours, doesn't work. Well how frustrating is that? : /

    var links = document.getElementsByTagName("a");

    for(x = 0; x < links.lenght; x++) {

    links[x].className = "foo";


  5. Hey! Great videos and well explained! I just have a little question. Is there a possibility to check if an element has 2 specific attributes? For example I want to check if an element is an anchor (a attribute) and has specific class, for example class="link". If so, store this element (or more elements if more than one can be found) in a variable.

  6. I have a question

    The aim of this demo was to assign "class" to all links. Instead of doing it in HTML we used JAVA-SCRIPT to assign class to all links.


    correct me if i am wrong…


Please enter your comment!
Please enter your name here