Get all custom DOM properties

I add DOM properties to the element dynamically as follows:

i = 0;
document.body['a' + i] = "foo";
document.body['b' + i] = "bar";

Is there a way to get all the properties that I attached as an array? Example:

var allProperties = ['a0', 'b0'];

Thank!

+4
source share
2 answers

In fact, you can create a new body object and compare with this object to get properties not added by the browser

i = 0;
document.body['a' + i] = "foo";
document.body['b' + i] = "bar";

var el  = document.createElement('body'),
    arr = [];

for (var key in document.body) {
    if (document.body.hasOwnProperty(key) && !(key in el)) {
        arr.push(key);
    }
}

Fiddle

will be a little more fantastic

var el  = document.createElement('body'),
    arr = Object.keys(document.body).filter(function(prop) {
        return !(prop in el);
    });
+4
source

Add a property with a fixed name in the element you are interested in and click custom properties

var pushInto = function(element, name, value)
{
    element[name] = value;
    if (element["customProperties"] == undefined)
    {
         element["customProperties"] = [];
    }
    element["customProperties"].push(name);
}

Then you can do:

pushInto(document.body, "name", "value");
document.body["customProperties"]; // ["name"]
0
source

Source: https://habr.com/ru/post/1530998/


All Articles