我正在玩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;未定义的
答案 0 :(得分:1)
下面的演示展示了如何使用innerHtml和getElementsByClassName方法将getElementById从一个元素转移到另一个元素。
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>