Function that returns TRUE if Object contains Property

Function that returns TRUE if Object contains Property
0

Hello Everyone,

I’ve been stuck on this all day. I’m looking for a function that returns true if a property exists within an object regardless if its = “”, null, undefined, etc. When I load this file in my browser, I get false, but I know the tagName property = “P” and Google Chrome Developer Tools shows that the tagName property exists. Please help!

    <script>
        window.onload = function() {
            
            var $ = function(id) {
                return document.getElementById(id);
            };
                        
            var doesPropExist = function(object,property) {
                var propLookUp = Object.prototype.hasOwnProperty.call(object,property);
                console.log(propLookUp);
            }
            
            doesPropExist($("p1"),'tagName'); 
            /*Above logs FALSE in console, but tagName is a property of the paragraph element. Why is it happening and how do I fix?*/
                
            };
    </script>
</head>

<body>   
    <main>
        <p id="p1">Paragraph 1</p>
    </main>
</body>

From the documentation:

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)

(emphasis mine)

It is inherited, so the object itself does not have that property.

Also, any reason why you’re doing

Object.prototype.hasOwnProperty.call(object,property);

instead of

object.hasOwnProperty(property)

get ElementById returns a DOM Element, which as @DanCouper pointed out, inherits all of its properties, so hasOwnProperty will never return true in this case.

You can always check the value of a property by using array notation. So you can do object[property] to get the value. Of course if the property doesn’t exist on the object then that will return undefined, which is a perfectly valid value, so you won’t be able to tell if the property just has the value undefined or if the property doesn’t exist in the first place.

Instead, you can use a for…in statement to go through every property in the object (inherited or not).

for (let key in object) {
   if (key === property) return true;
}
return false;

Note that this will go through every property in the object, which includes functions, event objects, other DOM objects. So if you wanted to limit the types of properties to look for you could use type of to weed out the ones you don’t want.

Thank you. Very helpful!