Reputation:
I am playing around with TypeScript and am trying to create a script that will fetch the HTML values of a div with class and id.
However, I am able to get the result for a class but I cannot fetch the result using getElementById
.
The html looks as following:
<button (click)="selectDiv()">select div</button>
<div class="container" id="main-wrapper">
<p>
Fetch me
</p>
</div>
And the explore.ts
file
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
is giving me an error as follows:
ERROR TypeError: Cannot read property 'innerHTML' of undefined
Upvotes: 0
Views: 1629
Reputation: 1718
The demo below shows how to transfer innerHtml from one element to another using both the getElementsByClassName and getElementById methods.
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>
Typescript
selectDiv = () => {
document.getElementById("containerDivByIdResults").innerHTML = document.getElementById("main-wrapper").innerHTML;
document.getElementById("containerDivByClassResults").innerHTML = document.getElementsByClassName("container")[0].innerHTML;
}
Upvotes: 1
Reputation: 28529
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>
Upvotes: 1