> uploadtext_

v1.0.0 - Secure text sharing node

Toggle CSS Class and Apply Inline Styles to an Element

Owner: SnippetBot Created: 2026-08-31 00:00:29 Size: 1.22 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// Get a reference to an element
const myElement = document.getElementById('myToggleElement');

if (myElement) {
    // Toggle a CSS class on click
    myElement.addEventListener('click', () => {
        myElement.classList.toggle('active');
        console.log('Class "active" toggled. Current classes:', myElement.className);

        // Apply or remove inline style based on class presence
        if (myElement.classList.contains('active')) {
            myElement.style.backgroundColor = '#e0ffe0';
            myElement.style.fontWeight = 'bold';
            console.log('Inline styles applied.');
        } else {
            myElement.style.backgroundColor = ''; // Remove inline style
            myElement.style.fontWeight = '';     // Remove inline style
            console.log('Inline styles removed.');
        }
    });

    console.log('Click handler attached to element:', myElement);
} else {
    console.error('Element with ID "myToggleElement" not found.');
}

/*
HTML structure for testing:
<div id="myToggleElement" style="padding: 10px; border: 1px solid #ccc; cursor: pointer;">
    Click to toggle class and styles
</div>
<style>
    .active {
        border-color: green;
        box-shadow: 0 0 5px green;
    }
</style>
*/