Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTMLElement from Element

I have an Element, and I can not figure out how to get the HTMLElement from it.

For example:

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

I then get them like so:

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'; } 
like image 794
Get Off My Lawn Avatar asked Jul 06 '16 22:07

Get Off My Lawn


1 Answers

You just need to cast it:

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 cast to a more specific element:

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

The thing is that document.querySelectorAll returns the most generic element type, but if you know yourself what is the specific type then you can cast, because you "know better" than the compiler.

like image 58
Nitzan Tomer Avatar answered Sep 20 '22 09:09

Nitzan Tomer