The code you posted doesn't won't work as you expect, what you're doing here is checking if the attribute-value of the named attribute ("data-params") is equal to "undefined", which will return true only if the attribute is data-params="undefined".
if (object.getAttribute("data-params") === "undefined") {
// the "data-params" attribute-value is exactly "undefined"
// note that `getAttribute()` is a
}
What I suspect you want to do is:
var typeOfObjectAttribute = typeof object.getAttribute("data-params");
if (typeOfObjectAttribute === null || typeOfObjectAttribute === "") {
// data-params attribute doesn't exist on that Node.
}
Note that – according Mozilla Developer Network (at the reference for Element.getAttribute(), below) – states that:
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string)…
It's also worth noting that getAttribute() is a method of the Element nodes, rather than generic objects.
Incidentally, you could also use the following approach (again, testing that the attribute is not set):
// here we look to see if the 'params' key is present in the
// HTMLElement.dataset object of the element, and then invert
// that result using the '!' operator, to check that the
// attribute *isn't* present:
if (!('params' in document.getElementById('elementID').dataset)) {
// the data-params attribute is not present.
}
The HTMLElement.dataset read-only property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.
Sadly this will not work in IE10 but i am pretty sure that there is a shim out there somewhere.
Here is an example
var containerData = document.querySelector('#container').dataset,
contentData = document.querySelector('#content').dataset;
// Check if dataset is empty or not.
console.log(Object.keys(containerData).length === 0);
console.log(Object.keys(contentData).length === 0);
// Check for specific data
if (containerData.hasOwnProperty('bar')) {
console.log(containerData.bar);
}
// Here is the dataset
console.log(containerData);