javascripthtmlcss

Reposition class element


I have an eye icon and when you click on it the icon changes and it repositions via js: left: 10%;.

However, if there is an element in the DOM with the ID login-section, it should be repositioned to left: 50%;.

I tried document.getElementsByClassName('fa-eye-slash').style.left = '50%'; but that doesn't work.

let eye = document.querySelectorAll('.eye');
eye.forEach(function (v) {
    v.addEventListener('click', function () {
        this.classList.toggle('fa-eye-slash');
    

        if(document.getElementById('login-section')) {
            // Following line is not working:
            document.getElementsByClassName('fa-eye-slash').style.left = '50%';
        }
       

    })
});
.eye {
    position: absolute;
}
.fa-eye-slash {
    left: 10%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div id='login-section'>
    <i class="fa-solid fa-eye eye"></i>
</div>


Solution

  • You should select the element itself that was clicked and has the class .fa-eye-slash. Right now, it looks like you are trying to set the left property of all elements with the class .fa-eye-slash.

    Additionally, you can use the style property to set the CSS style. But, since you want to toggle between two positions, it might be better to add and remove a CSS class that defines the left property.

    Here's an example that might be helpful:

    let eye = document.querySelectorAll('.eye');
    
    eye.forEach(function (v) {
        v.addEventListener('click', function () {
            this.classList.toggle('fa-eye-slash');
    
            if (document.getElementById('login-section')) {
                if (this.classList.contains('fa-eye-slash')) {
                    this.style.left = '50%'; 
                } else {
                    this.style.left = '10%'; 
                }
            }
        });
    });