Alex
Alex

Reputation: 2072

JavaScript - anyway to remove all base methods and attributes of an Object but keep one?

I'm building some app which scans the DOM for elements and their children. Right now, I can get the data I need with the following line of code:

var bodyObj = document.getElementsByTagName("BODY")[0].children;

The problem, that the bodyObj object is spammed with unnecessary methods and attributes, I only want to keep the children method and clean the rest. Any way of achieving this?

PS Pure Js.

Upvotes: 0

Views: 129

Answers (2)

Hutch Moore
Hutch Moore

Reputation: 132

Body object with only the children property

You might think to try something like:

var bodyObj = document.getElementsByTagName("BODY")[0];

for (var key in bodyObj){
    if (bodyObj.hasOwnProperty(key) && key != 'children'){
        delete bodyObj[key];
    }
}

...like Florian Cabirol suggested in their answer. However, the <body> object's properties are non-enumerable, meaning they won't show up in the loop. To get the non-enumerable properties, you might try (in ES5+):

Object.getOwnPropertyNames(bodyObj);

But it still won't get them. Next, you might think, "I'll just make an array of all possible property/method names that are in HTMLBodyElements, and loop through them, removing them if they exist." However, if you do something like:

delete bodyObj.baseURI;
console.log(bodyObj.baseURI);

You'll notice that it didn't delete it. That's because you can't remove properties from a DOM object. Attempts to redefine them or to delete them will silently fail.

Body object's children's HTMLElements

To get document.getElementsByTagName("BODY")[0].children without any of its properties/methods, you could do:

var bodyObj = document.getElementsByTagName("BODY")[0].children;

bodyObj = Object.keys(bodyObj).map(function(key) { return bodyObj[key]; });

This would convert it from an HTMLCollection to an array, if you're okay with that. You could always wrap it in an object: bodyObj = {children: bodyObj};.

Upvotes: 2

Florian Cabirol
Florian Cabirol

Reputation: 185

You can do something like this :

for (var key in bodyObj){
    if (bodyObj.hasOwnProperty(key) && key != 'children'){
        delete bodyObj[key];
    }
}

Upvotes: 0

Related Questions