Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element is a script [closed]

I'm gathering a random element from the DOM with javascript. How can I check something likewise "if element is a script, do something" ()?

like image 205
Joheo Avatar asked Jan 20 '26 00:01

Joheo


1 Answers

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) {
}
like image 71
plalx Avatar answered Jan 22 '26 13:01

plalx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!