document.getElementById未返回任何值

时间:2017-05-30 02:15:37

标签: javascript html getelementbyid

我正在玩TypeScript,我正在尝试创建一个脚本,用于获取带有class和id的div的HTML值。

但是,我能够获得课程的结果,但我无法使用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给出了如下错误:

  

错误类型错误:无法读取属性&lt; innerHTML&#39;未定义的

2 个答案:

答案 0 :(得分:1)

下面的演示展示了如何使用innerHtmlgetElementsByClassName方法将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;
}

答案 1 :(得分:1)

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>