How to select classes using Document.querySelector() that only appear after a condition is met?

I have a classname that appears only when the visibility is true. How can i select it?

I’m not quite sure I understand the problem completely. Maybe you can give us a link to your project so we can test for ourselves?

If you want to select an element with a certain class on it then the class must be there before you can select it. If the the class isn’t on the element perhaps there is something else you can use to select it?

1 Like

Here is my GitHub GitHub - AnkurC7/To-Do-List-App: This app helps us to track everything from our daily activities to things

Here is the app link To Do List App

In the Tasks.js file I have my div component set up as this:

      className={`container ${
        showAddTask ? "containerGlass container2" : " "

That is if the state named showaddTask is true then it sets the className as container2. I was trying to select that container2 and give it some styling/properties.

If you look at my app link in my website you can see that the tasks tilt.

When I click Add Task the showAddTask state is true thus giving my above div the class of container2 and containerGlass.

I wanted to select and style container2 that is when I click Add Task only then I wanted to tilt the whole thing that is the container with the list of tasks and not from the very beginning that’s why i was trying to select container2 only.

I can style container2 using CSS but cannot select it using the document query selector because I guess what it does it looks through the document and tries to find a class name container2 which does not exist if we look at the developer tools. But it exists when we click Add Task. So I was wondering how I could select container2 and give it some properties.

You’re approaching this from the wrong side.

Conventional JS/jQuery approach:

  • build the DOM
  • some state changes
  • manipulate the DOM directly as a response to that state change

React approach:

  • render the DOM
  • some state changes
  • render a different DOM

You don’t need querySelector in React to select a DOM element. Your React code renders the DOM. If you want to do something with an element when the state changes, you render it differently.

If you want to change its CSS, you can directly pass a style object, or you can give it a different class (like you tried to do).

Also, what’s that $ character doing here?

className={`container ${
        showAddTask ? "containerGlass container2" : " "
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.