Get an HTMLElement element from an element

I have an Element and I cannot figure out how to get an HTMLElement from it.

For instance:

 <a href="">A link</a> <a href="">Another link</a> 

Then I get them like this:

 var nodes: NodeListOf<Element> = document.querySelectorAll('a'); // Returns a NodeList of Elements for (let i = 0; i < nodes.length; i++) { var node = nodes.item(i); // How can I get the HTMLElement here? } 

Edit

enter image description here

Here is the code:

 let nodes: NodeListOf<Element> = document.querySelectorAll('a'); for (let i = 0; nodes[i]; i++) { let node = nodes[i]; var c = nodes[i].style.backgroundColor = 'red'; } 
+6
source share
3 answers

You just need to do this:

 let nodes = document.querySelectorAll('a'); for (let i = 0; nodes[i]; i++) { let node = nodes[i]; var c = (nodes[i] as HTMLElement).style.backgroundColor = 'red'; } 

You can even apply a more specific element:

 (nodes[i] as HTMLAnchorElement).style.backgroundColor = 'red'; 

The fact is that document.querySelectorAll returns the most general type of element, but if you know yourself what a particular type is, then you can use it because you "know better" than the compiler.

+10
source

You are close!

 var nodes = document.querySelectorAll('a'); // Returns a NodeList of Elements for (let i = 0; nodes[i]; i++) { // node is your element! var node = nodes[i]; node.style.backgroundColor = "blue"; } 
+2
source

The way this works is to pass an element to an HTMLElement .

 let nodes: NodeListOf<HTMLElement> = document.querySelectorAll('a') as NodeListOf<HTMLElement>; 
0
source

All Articles