Is there some way for check if an html attribute is not part of DOM HTML5?

Viewed 86

I've been trying to check if some attributes are not part of DOM HTML5 attributes. The code traverses the html markup and save on a Set. My idea is to identify in this example the attributes ng-controller, ng-repeat, ng-bind because the other attributes (id and class) are part of DOM HTML5 attributes.

HTML

<div id="html-markup">
        <div class="class-1" ng-controller="myController">
            <table id="the-table">
                <thead class="table-header" >
                        <th ng-repeat="(key, val) in myList[0] track by key">
                            {{ key }}
                        </th>
                </thead>
                <tbody class="table-body">
                    <tr ng-repeat="item in myList track by item.id">
                        <td ng-repeat="(key, value) in item">
                            <span ng-bind="value"></span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

Javascript

const element = document.getElementById("html-markup");
const allChildrensNodes = element.childNodes;
const allChildrensElements = element.getElementsByTagName("*");
const attributesArray = Array.from(allChildrensElements)
        .reduce((set, child) => {
            Array.from(child.attributes).forEach((attr) => {
                //if(ATTRIBUTE IS NOT PART OF DOM HTML5 ATTRIBUTES)
                set.add(attr.name)
            });
            return set;
        }, new Set())

console.log(attributesArray);//Set(5) {"class", "ng-controller", "id", "ng-repeat", "ng-bind"}

Is there some hack or trick to check this?

a codepen for play with this: https://codepen.io/gpincheiraa/pen/veWKOj?editors=1010

2 Answers

I don't believe there's any short-cut here. You'll have to build a list of the valid attributes per tag type (and note some are only valid when others have a particular value) based on the spec. While many attributes have reflected properties you could check for, A) Not all do, B) the names of the reflected properties are not always the same as the attributes they reflect; C) some properties have the same name as attributes but aren't directly reflected (though they're usually related in some way, even if loosely; value isn't a reflected property for the value attribute, for instance; the property is defaultValue).

Hi If you want to collect start with "ng-" you can add below code insted`

if(attr.name.startsWith('ng-'))
  set.add(attr.name)

Or you can make your own array with full attribute list in in this link (HTML attribute reference)

    const fullAttributeList = ['class','name','id',.....];
   ..
   ..
   ..
    if(fullAttributeList.indexOf(attr.name) ===-1)
      set.add(attr.name)
Related