document.getElementById 没有返回任何值

document.getElementById is not returning any value

我正在使用 TypeScript 并尝试创建一个脚本,该脚本将使用 class 和 id.

获取 div 的 HTML 值

但是,我能够获得 class 的结果,但我无法使用 getElementById 获取结果。

html 如下所示:

<button (click)="selectDiv()">select div</button>

   <div class="container"  id="main-wrapper">   
<p>
 Fetch me
</p>
</div> 

explore.ts 文件

selectDiv() {
     //create a new HTMLElement from nativeElement
    var hElement: HTMLElement = this.elRef.nativeElement;

    //now you can simply get your elements with their class name
   var allDivs = hElement.getElementsByClassName('container')[0];

   var getSection = <HTMLElement>document.getElementById["main-wrapper"].innerHTML;

    console.log(allDivs);
    console.log(getSection); // returning nothing
  }

getsection 给我一个错误如下:

ERROR TypeError: Cannot read property 'innerHTML' of undefined

下面的演示展示了如何传输 innerHtml from one element to another using both the getElementsByClassName and getElementById 方法。

Working JSFiddle demo

HTML

<button onclick="selectDiv()">select div</button>

<div class="container" id="main-wrapper">
  <p>
    Fetch me
  </p>
</div>

<div id="containerDivByIdResults">

</div>

<div id="containerDivByClassResults">

</div>

打字稿

selectDiv = () => {
  document.getElementById("containerDivByIdResults").innerHTML = document.getElementById("main-wrapper").innerHTML;
  document.getElementById("containerDivByClassResults").innerHTML = document.getElementsByClassName("container")[0].innerHTML;
}

function selectDiv() {
     //create a new HTMLElement from nativeElement
   // var hElement: HTMLElement = this.elRef.nativeElement;

    //now you can simply get your elements with their class name
   var allDivs = document.getElementsByClassName('container')[0];

   var getSection = document.getElementById("main-wrapper").innerHTML;

    console.log(allDivs);
    console.log(getSection); // returning nothing
  }
<button onclick="selectDiv()">select div</button>

   <div class="container"  id="main-wrapper">   
<p>
 Fetch me
</p>
</div>