KESO
KESO

Reputation: 335

TypeScript - Property 'id' does not exist on type 'Node'

I got this issue working with TypeScript (for Angular2) when I try to get the id of an element. See this example:

<div id="search">
    <div id="field1"></div>
    <div id="field2"></div>
</div>

If I try to get the id of one of the nested div, I can do this normally:

var element = document.getElementById("search");
var subelement = element.childNodes;
subelement[1].id;

Then I will have "field2".

However when I try to do this with TypeScript I got the message Property 'id' does not exist on type 'Node'. And as result my code doesn't work. I really need a solution for this since I need to know the nested elements inside another, unless there are a better way.

Upvotes: 8

Views: 16885

Answers (3)

jamsheed
jamsheed

Reputation: 21

error TS2551: Property 'setAttribute' does not exist on type 'Node'. Did you mean 'attributes'?

const elements = document.querySelectorAll("text");

elements[k].style.transform = '...........';////error

elements[k]['style'].transform = '..........';//is working

elements[k].parentNode.setAttribute('....');////error

elements[k].parentNode['setAttribute']('..');//is working

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202176

I would use document.getElementById to reference a DOM element in Angular2 but rather leverages @ViewChild like this:

@Component({
  (...)
  template: `
    <div #search>
      <div id="field1"></div>
      <div id="field2"></div>
    </div>
  `
})
export class SomeComponent {
  @ViewChild('search') searchElement:ElementRef;

  ngAfterViewInit() {
    let domElement = searchElement.nativeElement;
    (...)
  }
}

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190945

Nodes can be more than just elements and don't necessarily have an id property. You should use .children which is a collection of elements only.

Upvotes: 10

Related Questions