Wednesday, February 19, 2025

JavaScript, How to loop through each property of document object where propert is not event?

How to loop through each property of document object where propert is not event?


To loop through each property of the document object in JavaScript, while excluding properties that are events, you can use a for...in loop. By checking the type of each property, you can filter out the event properties.

Here’s how you can do it:



for (let prop in document) {
    if (typeof document[prop] !== 'function' && !prop.startsWith('on')) {
        console.log(`${prop}: ${document[prop]}`);
    }
}
Explanation
for...in loop iterates over all enumerable properties of the document object.
typeof document[prop] !== 'function': Filters out properties that are functions (which are typically event handlers).
!prop.startsWith('on'): Skips properties that start with 'on', as they usually represent events (like onclick, onload, etc.).
This will log only non-event, non-function properties of the document object.

No comments:

Post a Comment

Hot Topics