gharel
gharel

Reputation: 573

What is the use for HTMLSpanElement (and others)

I am learning javascript.

var label = document.getElementById('lblMsg');

If I inspect the element with F12, its described as an HTMLSpanElement. I cannot cast the element to its type, like:

var label = (HTMLSpanElement) document.getElementById('lblMsg');

So whats the use for HTMLSpanElement ? Does it have any properties différent than the other HTMLElements ?

Upvotes: 3

Views: 3334

Answers (1)

GOTO 0
GOTO 0

Reputation: 47652

Since you are a beginner, I'm going to point out a few basic facts that may help you make some sense of what you are observing.

JavaScript is weakly typed

Objects in JavaScript do have types, but variables are not typed, i.e. any variable can take any object of any type. Type casting is not necessary, nor is it possible (and in fact the line (HTMLSpanElement) document.getElementById('lblMsg') is a syntax error).

HTML elements types

HTMLSpanElement is a type. Well, not really. It's a DOM interface, which is treated as a native object type by all modern browsers for convenience. Most HTML elements have the type of their main interface.

The point of interfaces is to expose a set of methods, properties or events available to all implementations. You already have the MDN link for HTMLSpanElement: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement.

Testing for a type

To test if an object is an instance of a particular type, we can use obj instanceof Type. In this case:

if (document.getElementById('lblMsg') instanceof HTMLSpanElement)
{
    ...
}

Type inheritance is always honored.

document.getElementById('lblMsg') instanceof Object // true

Getting an object's type

To get the type of an HTML element, we use element.constructor, as in

document.getElementById('lblMsg').constructor

If you enter this in the browser console, you will see something like

`function HTMLSpanElement() { [native code] }`

Don't be surprised. Object types are functions in JavaScript. If we were just interested in the name of this object's type, we could use

document.getElementById('lblMsg').constructor.name

Which yields the string "HTMLSpanElement"

This method of determining an object's type is not 100% foolproof, but it works for all builtin objects.

Upvotes: 5

Related Questions