Reputation: 11671
I get error when I try to get the content of meta tag:
document.getElementById('mymetatag').content
in Javascript is works, but typescript say that
Property 'content' does not exist on type 'HTMLElement'
So how to extend the HTMLElement type interface to support content property?
Upvotes: 7
Views: 12046
Reputation: 16644
Can use getAttribute method:
document.getElementById('mymetatag').getAttribute('content')
Upvotes: 0
Reputation: 61
Also, for <template id="source">
, you can use HTMLTemplateElement
const source = document.querySelector('#source') as HTMLTemplateElement;
const sourceClone = source.content.cloneNode(true) as HTMLElement;
Upvotes: 4
Reputation: 25850
TypeScript doesn't know what kind of element has this specific ID. It cannot trust the element even exists to begin with!
You need to introduce another check in order to validate your assumption:
const element: HTMLElement | null = document.getElementById('mymetatag');
if (element instanceof HTMLMetaElement) {
element.content;
}
Update
You can also use assertion signatures.
function assert(condition: boolean, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
Then your solution becomes:
const element: HTMLElement | null = document.getElementById('mymetatag');
assert(element instanceof HTMLMetaElement, "A <meta> element of id 'mymetatag' needs to exist in the DOM.");
element.content; // string
Upvotes: 13
Reputation: 5645
Try following:
(<HTMLMetaElement> document.getElementById("mymetatag")).content;
Upvotes: 0
Reputation: 1908
document.getElementById()
returns an HTMLElement
.
But you know that your result is a meta tag, which is a type of HTMLMetaElement
.
Looking at the docs you can see that HTMLElement
is the ancestor of HTMLMetaElement
so you should downcast your element to this type. You can do this with two different syntaxes:
const metaElement = document.getElementById("mymetatag") as HTMLMetaElement;
// Or the second version:
//const metaElement = <HTMLMetaElement>document.getElementById("mymetatag");
const metaContent = metaElement.content;
See more about type assertions here.
Upvotes: 1