I have combined the getElementsByTagName and getAttribute methods to get the title attribute of every paragraph element in the document. Here is the code:
var paras = document.getElementsByTagName('p');
for (i = 0; i < paras.length; i++) {
console.log(paras[i].getAttribute('title'));
}
The line of code I am specifically need assistance with is this one:
console.log(paras[i].getAttribute('title'));
What is the [i] doing within this line of code? Is this the ‘counter’ variable that I declared in the for loop that is incrementing on each iteration? And is the [i] also representative of the index of the array that is returned by the getElementsByTagName function?
The key here is getElementsByTagName returns a
NodeList.You are then looping over the NodeList (which can be thought of as an array) with you for loop. The value of
igoes from0to the length of the array -1.So to answer your question. Yes,
iis the index and when you sayparas[i]you are asking for the element at indexi.For example, given the following html:
If you called
paras = document.getElementsByTagName("p")it would return an array with 3 elements.At
paras[0]would be the p with id a.At
paras[1]would be the p with id b.At
paras[2]would be the p with id c.