Reputation: 24935
I was wondering if there is a way to check if an element is in-built or custom element.
I know one option using element.constructor.name
, to check if its not HTMLUnknownElement. But the question is, how does the engine determines if element is unknown element or known element.
Following is a sample:
var elements = document.querySelectorAll('.content > *');
Array.from(elements).forEach(el => {
console.log(el.constructor.name)
})
<div class='content'>
<test-element>Test Element</test-element>
<testElement>Dummy</testElement>
</div>
If you notice, adding hyphens(-
) makes engine to process it as a known element.
So is there a concrete way to determine if the element is unknown element?
Upvotes: 2
Views: 914
Reputation: 4065
You can use customElements.get()
to check if an element has been registered as a custom element. For example
/** @param {HTMLElement} element */
function isCustomElement(element) {
const tagName = element.tagName.toLowerCase()
return Boolean(customElements.get(tagName))
}
Usage
for (const el of document.querySelectorAll('.content > *')) {
console.log(el.tagName, isCustomElement(el))
}
Upvotes: 0
Reputation: 65795
Not sure about a fool-proof way (maybe invoke a DOM Parser?), but if you could determine the naming conventions that cause problems getting accurate results, you could use a regular expression to filter the characters causing the issue out, create a "dummy" element from the corrected nodeName
and then test the dummy:
var elements = document.querySelectorAll('.content > *');
Array.from(elements).forEach(el => {
var dummy = document.createElement(el.nodeName.replace(/-+/, ""));
console.log(dummy.constructor.name)
})
<div class='content'>
<test-element>Test Element</test-element>
<testElement>Dummy</testElement>
</div>
You could also take the element and make it part of an XHTML dummy document and then validate that document using an XML Parser against the XHTML schema/DTD, but I don't believe there is a standard one for XHTML5. Anyway, here's some code that will at least convert your test HTML strings into XHTML syntax. The next step would be to programatically validate it.
const parser = new DOMParser();
var elements = document.querySelectorAll('.content > *');
Array.from(elements).forEach(el => {
var doc = parser.parseFromString(el.outerHTML, "text/html");
var result = new XMLSerializer().serializeToString(doc);
console.log(result);
})
<div class='content'>
<test-element>Test Element</test-element>
<testElement>Dummy</testElement>
</div>
I also found this HTML Tag Validator as a Node Package
Upvotes: 1