Attributes and Properties
Element Attributes
HTML elements can have attributes, like id, class, src, etc. You can work with these in JavaScript:
-
Check if an attribute exists:
element.hasAttribute('attributeName')
-
Get the value of an attribute:
element.getAttribute('attributeName')
-
Set the value of an attribute:
element.setAttribute('attributeName', 'value')
-
Remove an attribute:
element.removeAttribute('attributeName')
Element Properties
Most HTML attributes have corresponding JavaScript properties. For example, the id attribute corresponds to the id property:
let div = document.querySelector('div');
console.log(div.id); // Reads the 'id' attribute
div.id = 'new-id'; // Sets the 'id' attribute
Document Structure and Content
You can access key parts of the document easily:
document.documentElement
: The<html>
tagdocument.body
: The<body>
tagdocument.head
: The<head>
tag
console.log(document.body.tagName); // "BODY"