I'm gathering a random element from the DOM with javascript. How can I check something likewise "if element is a script, do something" ()?
There's multiple ways to do it, depending on the level of robustness you need.
If you only deal with DOM elements of an <!DOCTYPE html> document then the following is enough:
if (el.tagName === 'SCRIPT') {
}
Note that since el.tagName is not always guaranteed to be in upper-case for all doctypes you may want:
if (el.tagName.toUpperCase() === 'SCRIPT') {
}
If you're not sure which type of object you're dealing with, you can still use duck typing:
if (el && el.tagName && el.tagName.toUpperCase() === 'SCRIPT') {
}
Or make an even stricter check in modern browsers with:
if (el instanceof HTMLScriptElement) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With