Get innerHtml with forEach loop
I want to get the innerHTML of h1 element here, what am I doing wrong here
39 Replies
It's returning an array, you want
block.querySelectorAll('.card h1')[0]
However you should only have 1 h1
on your page so you should use document.getElementsByTagName('h1')[0]
. It's also worth moving this to before the forEach
because you don't need to query it on every iterationCan't you just use
document.querySelector("h1")
and not need to use array syntax?i have 5 h1
and want to make changes to all 5
You can, but there is a method specifically for selecting tage
this is what i am getting now
It's really, really recommended that you do not use 5 h1s but only 1 like ProblemSolver said
It's bad for SEO if you do use more than 1 and not semantic
Aha, so firstly turn them into h2s, you can have many of those
Secondly when looping through the
removeLastElements
it's already selected the h1
from them (via oshBlockH1
) so you can just use block
as the h1
Remove the rest syntax from oshBlockH1
The [...]
I could be wrong but that might be making a 2d array
No it needs that
Why? Isn't it already an array
It's a NodeList rather than an array
if i remove rest it gives this errror
Ohhh dang
Yes sorry listen to ProblemSolver
They know more about JS than I do haha
how can i turn nodelist to array?
You already did with the rest syntax
That's the way I do it, using the spread operator
[...document.querySelectorAll('???')]
new Array(...document.querySelectorAll('???'))
You can also use Array.from() 🙂
But spread operator/rest syntax is more modern
I assume they all perform exactly the same, it should be something even JS can optimise out
look i am getting all the h1's but its innerHtml is null
Is
h
still a NodeList?how do i extract this values
Did you try .innerText?
removeLastElement.map(element => console.log(element.innerText);
Ah so its still a nodelist
yes
Is there only one h1 inside every card?
yes
My personal tool for that is block.querySelector(".card h1").innerText
I still strongly advise you not to use more than 1 h1 tag for one page, they should be h3s honestly for the cards assuming they're in a section which has an h2 tag for the header
tried that but i got this error
block
should be an h1 tho, you don't need to query or select anything you already have itYou're right
look this is my card element
Why are you removing the last element from it anyway if a card only has one h1?
coz last h1 has different value which is not needed
Okay I think I understand now
I'm on mobile so it's gonna take me a second to type up
i have 6 cards all have h1
ok I got the solution, I need to loop the card instead of h1
you were right
thanks 👍
Awesome 🙂