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>
The getElementById() method returns the element that has the ID attribute with the specified value. [....] Returns null if no elements with the specified ID exists.
So it returns an HTMLElement Object
source
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:
ElementgetElementByIdElement on MDNgetElementById on MDNI 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With