0

Given the following html:

<div class="container">
    <form class="form" id="login">
        <h1 class="form__title">Login</h1>
        <div class="form__message form__message-error"></div>
    </form>
</div>

Is there an easy way to reference the element of class "form__message" ? I know this is the only element of this class in this example, but potentially there could be more. So I was trying the following to remove the form__message-error CSS-properties:

 $("#login .form__message").classList.add("form__message--error");

This, however, does not find the correct element, whereas the following works:

document.querySelector("#login").querySelector(".form__message").classList.remove("form__message--error");

I am looking for a jQuery alternative to the last statement.

Luk
  • 1,009
  • 2
  • 15
  • 33
  • 3
    `$("#login .form__message").classList.add("form__message--error");` is not jQuery - you want `$("#login .form__message").addClass("form__message--error");` and `$("#login .form__message").removeClass("form__message--error");` OR `$("#login .form__message").toggleClass("form__message--error");` – mplungjan Nov 09 '21 at 15:16
  • Hey, try something like this $(".form__message","#login").removeClass("form__message--error") – jPO Nov 09 '21 at 15:17
  • 1
    Why would `.classList.add()` *remove* a class? – Heretic Monkey Nov 09 '21 at 15:17
  • `$('#login').find('.form__message').first().removeClass('form__message--error');` if you want the exact equivalent. – Heretic Monkey Nov 09 '21 at 15:19
  • Either use the jQuery `addClass` method (`$("#login .form__message").addClass("form__message--error");` [or `.removeClass`]) or the DOM's `classList` (`document.querySelector("#login .form__message").classList.add("form__message--error").classList.add("form__message--error");` [or `.remove`]). Note that that latter (and yours in the question) assumes there's only one match for the selector. If there may be more than one, to get the equivalent effect to the jQuery code, you need `querySelectorAll` and a loop. – T.J. Crowder Nov 09 '21 at 15:20
  • If you don't want to use jquery methods, you can always get the (first) DOM element using `[0]` : `$("#login .form__message")[0].classList...` – freedomn-m Nov 09 '21 at 15:21
  • See also [jquery find to get the first element](https://stackoverflow.com/q/2173971/215552) – Heretic Monkey Nov 09 '21 at 15:29

1 Answers1

0

You're mixing jQuery and DOM methods. The jQuery equivalent of .classList.add() is .addClass().

$("#login .form__message").addClass("form__message--error");

You don't need .find() with querySelector(), you can use the same selector as with jQuery:

document.querySelector("#login .form__message").classList.add("form__message--error");
Barmar
  • 741,623
  • 53
  • 500
  • 612