DOM Attribute and Style Control
HTML is represented as a tree of objects in the DOM. JavaScript’s DOM lets you select and edit web page elements, making them interactive. Once the desired elements have been chosen, manipulation is feasible. Properties and methods for locating items are provided by the document object.
Typical techniques for choosing components include:
- getElementById(): Gets the element with the specified unique ID.
- getElementsByTagName(): Returns a collection of elements with a specified tag name.
- getElementsByClassName(): Gets all elements with a specified class name.
- querySelector(): Gets the first element matching a specified CSS selector.
- querySelectorAll(): Gets a list of all elements matching specified CSS selectors.
The characteristics of an element can be altered after it has been chosen as a JavaScript object.
Manipulating Element Attributes
HTML elements are made up of a tag name and a collection of attributes, which are name/value pairs. Features such as id, class, href, src, and style give more details about an element. JavaScript can use these properties to change the element or add metadata.
As properties of the element’s DOM object, the values of frequently used standard attributes are frequently accessible directly. For instance, the equivalent element object may have the href attribute available as a href property.
Nonetheless, you must employ particular techniques in order to operate with any property, including bespoke ones or those that are not accessible as direct properties.
setAttribute(name, value): Modifies or sets the value of the provided attribute.
getAttribute(name): The value of the supplied attribute is returned by the getAttribute(name) function.
To work with element attributes generally, use setAttribute() and getAttribute(). Changing properties in this manner alters the page’s HTML, and you can observe these changes by looking at the developer tools in the browser.
Here’s a code example demonstrating attribute manipulation:
Assume we have an image element:
To change the src and add a title attribute:
<!DOCTYPE html>
<html>
<head>
<title>Corrected DOM Manipulation</title>
</head>
<body>
<h1>DOM Manipulation Example</h1>
<!– The image element we will manipulate –>
<img id=”myImage” src=”initial_image.jpg” alt=”Initial image”>
<script>
// Wrap the DOM manipulation code inside a DOMContentLoaded listener
document.addEventListener(‘DOMContentLoaded’, function() {
// Select the image element by ID
const imageElement = document.getElementById(‘myImage’);
// Check if the element was found
if (imageElement) {
console.log(“Image element found.”);
// Change the ‘src’ attribute using setAttribute()
// This will cause the browser to load ‘new_image.jpg’
imageElement.setAttribute(‘src’, ‘new_image.jpg’);
console.log(“Src attribute changed to ‘new_image.jpg’.”);
// Add or change the ‘title’ attribute using setAttribute()
// This sets the tooltip text for the image
imageElement.setAttribute(‘title’, ‘This is the new image’);
console.log(“Title attribute set.”);
// Get the value of the ‘alt’ attribute using getAttribute()
const altText = imageElement.getAttribute(‘alt’);
console.log(‘Original alt text was:’, altText); // Output: Original alt text was: Initial image
} else {
console.error(“Image element with ID ‘myImage’ not found!”);
}
});
</script>
</body>
</html>
Manipulating Element Styles
A web page’s display and layout are specified via the CSS language. It is possible to modify the CSS styles that are applied to components using JavaScript. Style can have an impact on how a document appears.
JavaScript allows for style manipulation in two main ways:
Directly modifying the style property: Making direct changes to the style property: A CSSStyleDeclaration object is the style property of every Element asset. You can access and set the corresponding properties on this style object to modify certain CSS properties. You may use e.style, for instance, to alter the border and background colour of an element e.”yellow” for the background colour or “1px solid black” for the e.style.border. By using this method, the HTML element’s style attribute is directly changed.
Modifying CSS classes: The more popular and frequently suggested method is to use CSS classes to define styles, and then use JavaScript to add, remove, or toggle these classes on elements. Although the class attribute can be changed, the className or classList properties are frequently a simpler way to do so. Because it offers methods for managing multiple classes on an element, such as add(), remove(), and toggle(), the classList property is especially helpful. Generally regarded as best practice, changing an element’s class permits the application of the CSS rules already in place for that class.
Here are code examples demonstrating style manipulation:
<!DOCTYPE html>
<html>
<head>
<title>Styled Paragraph Example</title>
<style>
.highlight {
color: blue;
font-weight: bold;
border: 2px dashed blue; /* Assuming a dashed border is desired */
}
/* Optional: Add a default style for the paragraph */
#styledParagraph {
padding: 10px; /* Example padding */
margin-bottom: 15px; /* Example margin */
border: 1px solid grey; /* Example default border */
}
</style>
</head>
<body>
<p id=”styledParagraph”>This paragraph will change style.</p>
<button id=”styleButton”>Change Style</button>
<button id=”classButton”>Toggle Class</button>
<script>
// Wait for the DOM to be fully loaded before running the script
document.addEventListener(‘DOMContentLoaded’, function() {
// Select the paragraph element by its ID
const paragraph = document.getElementById(‘styledParagraph’);
// Select the buttons by their IDs
const styleButton = document.getElementById(‘styleButton’);
const classButton = document.getElementById(‘classButton’);
// Check if all elements were found to prevent errors [Based on conversation history]
if (paragraph && styleButton && classButton) {
// Add an event listener to the “Change Style” button for the ‘click’ event
styleButton.addEventListener(‘click’, function() {
console.log(“Style button clicked.”); // Log action
// Directly change the style properties of the paragraph element
// CSS property names with hyphens are converted to camelCase in JavaScript
paragraph.style.color = ‘green’; // Set text color to green
paragraph.style.fontWeight = ‘normal’; // Set font weight back to normal
paragraph.style.border = ‘3px solid purple’; // Set border style
console.log(“Paragraph style changed directly.”); // Log action
});
// Add an event listener to the “Toggle Class” button for the ‘click’ event
classButton.addEventListener(‘click’, function() {
console.log(“Class button clicked.”); // Log action
// Toggle the ‘highlight’ class on the paragraph
// The toggle() method adds the class if it’s not present, and removes it if it is
paragraph.classList.toggle(‘highlight’);
console.log(“Toggled ‘highlight’ class on paragraph.”); // Log action
});
} else {
console.error(“One or more elements not found!”); // Log error [Based on conversation history]
}
});
</script>
</body>
</html>
More interactive user experiences can result from dynamically adjusting the look and behaviour of web page elements through the manipulation of element properties and styles.
Data Attributes
Data attributes are attributes that start with the prefix data- and have lowercase names. They were introduced in HTML5. These allow the addition of arbitrary data without changing the element’s appearance and are regarded as legitimate. JavaScript may readily read and alter this data. To prevent conflicts with other properties, it is advised to prefix custom attributes with data-.
In JavaScript, data characteristics can be changed in two main ways:
Using setAttribute(name, value) to set or modify a value and getAttribute(name) to retrieve a value. These techniques are supported by earlier browsers and can be used to any attribute, including data attributes.
The element object’s dataset attribute is being used. This property returns an object with the data-prefix removed, whose properties match the data-attributes. The camelCase properties (dataset.someDetail) are used to represent hyphenated data attribute names (data-some-detail). Working with data attributes is made easy with the dataset property, which provides a live interface. Dataset values are strings, so take note.
Here’s a code example:
<div id=”exampleDiv” data-id=”123″ data-user-name=”Alice”></div>
<script>
const div = document.getElementById(‘exampleDiv’);
// Using getAttribute and setAttribute
const userId = div.getAttribute(‘data-id’);
console.log(‘User ID (getAttribute):’, userId); // Output: User ID (getAttribute): 123
div.setAttribute(‘data-id’, ‘456’);
console.log(‘Updated data-id:’, div.getAttribute(‘data-id’)); // Output: Updated data-id: 456
// Using the dataset property
const userName = div.dataset.userName; // Accessing data-user-name as dataset.userName
console.log(‘User Name (dataset):’, userName); // Output: User Name (dataset): Alice
div.dataset.userName = ‘Bob’; // Setting data-user-name via dataset.userName
console.log(‘Updated data-user-name:’, div.getAttribute(‘data-user-name’)); // Output: Updated data-user-name: Bob
console.log(‘Updated dataset.userName:’, div.dataset.userName); // Output: Updated dataset.userName: Bob
</script>