Reputation: 69
What is the type of the variable "element" in this snippet? I thought it is a number (an ID or something), but now, I have no idea. The code works, but I don't understand, why the var element can be used in a for cycle, like an array. Is there any explanation about this?
<script type="text/javascript">
function showAtrributes() {
var element = document.getElementById("videos");
var listAttributes = "";
for(var attribute in element) {
var valueOfAtrrib = element.getAttribute(attribute);
listAttributes = listAttributes + attribute + ": " + valueOfAttrib + "\n";
}
alert(listAttributes);
}
</script>
Upvotes: 4
Views: 12462
Reputation: 4697
The return type can be anything that the programmer of a Web Browser defines to the JS VM library used, to create a specific implementation of Javascript. For instance, the webcwebbrowser which uses SpiderMonkey returns a JSObject of HTMLElement JSClass which it gets by calling CreateJSObject
on the underlying internal HTMLElement object. The JSObject is the internal VM library representation of objects visible to JS scripts, such as a HTMLElement. A HTMLElement in a script is actually accessing a JSObject logically instantiated from the HTMLElement JSClass, where JSObject and JSClasses are C++ classes. The HTMLElement JSObject also has a corresponding C++ native marshalled object of class HTMLElement.
Upvotes: 0
Reputation: 1075537
What is the return type of document.getElementById()
Element
. It returns a reference to the actual object for the element in the DOM (or null
if none was found with that id
). Details:
I thought it is a number (an ID or something)
No, that's "video"
(the string you used to look it up). It's also accessible from the id
property of the Element object.
The code works, but I don't understand, why the var element can be used in a for cycle, like an array.
for-in
isn't primarily for use on arrays, it's for use on objects. The only reason it works on arrays is that arrays are objects. (See this question's answers and this page on MDN for more on that.) DOM elements are objects, so you can loop through their enumerable properties via for-in
.
Upvotes: 5
Reputation: 376
It looks like you are really questioning why the for loop works, not what kind of object getElementById returns. Read this article:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
The for( var in ....) syntax causes Javascript to iterate over the properties of the object specified by ....
Upvotes: 0
Reputation: 1146
The return type of document.getElementById() is Element Object or null. Please Refer the following link from MDN:
Upvotes: 0