Element and Access in Context
Another important element in the DOM Core is, appropriately
enough, Element. All objects within a
document inherit a basic set of functionality and
properties from the Element. The
majority of the functionality has to do with getting and setting the
attributes, or checking for the existence of attributes:
getAttribute(name)setAttribute(name,value)removeAttribute(name)getAttributeNode(name)setAttributeNode(attr)removeAttributeNode(attr)hasAttribute(name)
There are other methods, most having to do with the namespaces associated with the attributes, but these aren’t methods you’ll typically use with a web page.
Attributes are not always properties. Attributes change by
element, with some elements having attributes such as width and align, while others don’t. Properties are a
component of the object class, rather than instances of the class. So
properties would be associated with the document object, Element, Node, or even the HTML elements such as
HTMLDocumentElement. But if you want
to work with an element’s attributes, and they’re not exposed as a
property on the object class, you’ll need to use these Element methods.
Here’s an image embedded in a web page:
<img src="dotty.gif" width="100" alt="an image" align="left" />
The following code accesses the image’s attributes, concatenating
them into a string, which is then printed in an alert:
var img = document.images[0]; var imgStr = img.getAttribute("src") + " " + img.getAttribute("width") ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access