0

Skipping a tag in JS

Does anyone know how you would skip a tag? For instance <p>Hello!</p> <p></p> <p></p> <p></p> I have some JS that is going to output 8 calculations to the p tags but I dont want the first p tag to be changed. I will have 9 p tags but the last 8 need change? JS is document.getElementsByTagName("p")[i].innerHTML = planetAge + " years old.";

13th Apr 2018, 5:56 PM
Angelina
Angelina - avatar
12 ответов
+ 4
Angelina Ahh that's what was required, link to the full code. Use '<=' (less than equal to) instead of < (less than) ;) for (i = 1; i <= planets.length; i++) and rest of the code as is! Edit: Because the index now starts from 1, so <= is mandatory to change the tag for every planet.
13th Apr 2018, 7:01 PM
Dev
Dev - avatar
+ 4
Angelina, use this and try again: for (i = 1; i < planets.length; i++) { var planetAge = age / planets[i - 1].orbit; document.getElementsByTagName("p")[i].innerHTML = planetAge + " years old."; }
13th Apr 2018, 6:37 PM
777
777 - avatar
+ 4
Angelina Oops, sorry I just messed it up. Check Rahul 's solution. That would work!
13th Apr 2018, 6:39 PM
Dev
Dev - avatar
+ 2
Are you using a for loop? You can just start i at 1 instead of 0
13th Apr 2018, 6:03 PM
Ariela
Ariela - avatar
+ 1
Use this: var array = document.getElementsByTagName(“p”; for(int i=1; i < array.length;i++){ array[i].innerHTML = text; } It won’t use the first, but will get the last
13th Apr 2018, 6:15 PM
Ariela
Ariela - avatar
+ 1
Doing the above doesn't calculate the correct ages :/
13th Apr 2018, 6:34 PM
Angelina
Angelina - avatar
+ 1
If it helps I have added code to my profile, also you can find it in codepen. https://codepen.io/angelinalblyth/pen/rdgbJd
13th Apr 2018, 6:52 PM
Angelina
Angelina - avatar
+ 1
Thank you so much! Didnt even think of that
13th Apr 2018, 7:04 PM
Angelina
Angelina - avatar
0
@Ariela If I do that then my last calculation is missed out as it has reached my .length by the time it gets to the last <p>
13th Apr 2018, 6:11 PM
Angelina
Angelina - avatar
0
Thats changing the first p tag again. This is the code I currently have and it works fine if I dont have the first p tag in my HTML. for (i = 0; i < planets.length; i++) { var planetAge = age / planets[i].orbit; document.getElementsByTagName("p")[i].innerHTML = planetAge + " years old."; }
13th Apr 2018, 6:20 PM
Angelina
Angelina - avatar
0
I didn't even see Rahul's solution, I have tried it and it still missing the last P tag and isn't replacing the text already in the P tag.
13th Apr 2018, 6:43 PM
Angelina
Angelina - avatar
0
does anyone know how to open a link in specific area of a webpage?
14th Apr 2018, 2:04 AM
PK BEHERA
PK BEHERA - avatar