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 :).
SUBSCRIBE TO CHANNEL – https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg?sub_confirmation=1
========== 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 – https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg or http://thenetninja.co.uk
========== Social Links ==========
Twitter – @TheNetNinja – https://twitter.com/thenetninjauk
Original source
8 responses to “JavaScript Tutorial For Beginners 19 – Practical Example using Loops”
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
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?
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?
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";
}
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.
why is this one trashed…i needed this
Please add #19 to video title
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.
Right??
correct me if i am wrong…