How to change other element properties?

076

To change other properties of an element in the DOM, you can use various properties and methods available on the element object. Here are some common ways to modify different properties:

1. Changing CSS Styles

You can change the inline styles of an element using the style property.

const element = document.getElementById('myElement');

// Change the background color
element.style.backgroundColor = 'lightblue';

// Change the font size
element.style.fontSize = '20px';

2. Changing Attributes

You can change attributes of an element using the setAttribute method or directly accessing the attribute.

const image = document.getElementById('myImage');

// Change the source of an image
image.setAttribute('src', 'newImage.jpg');

// Alternatively, you can access the attribute directly
image.src = 'newImage.jpg';

3. Changing Classes

You can add, remove, or toggle classes using the classList property.

const element = document.getElementById('myElement');

// Add a class
element.classList.add('newClass');

// Remove a class
element.classList.remove('oldClass');

// Toggle a class
element.classList.toggle('active');

4. Changing Element Visibility

You can change the visibility of an element by modifying its display or visibility style properties.

const element = document.getElementById('myElement');

// Hide the element
element.style.display = 'none';

// Show the element
element.style.display = 'block'; // or 'inline', 'inline-block', etc.

Example

Here’s a complete example that changes various properties of an element when a button is clicked:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Properties Example</title>
</head>
<body>
    <div id="myElement">This is a div element.</div>
    <button id="changeButton">Change Properties</button>

    <script>
        document.getElementById('changeButton').addEventListener('click', function() {
            const element = document.getElementById('myElement');
            element.style.backgroundColor = 'lightgreen'; // Change background color
            element.style.fontSize = '24px'; // Change font size
            element.classList.add('highlight'); // Add a class
        });
    </script>
</body>
</html>

In this example, clicking the button will change the background color, font size, and add a class to the div element.

0 Comments

no data
Be the first to share your comment!