How do I use JavaScript to make each trigger execute a function that only impacts its own child elements?

As I delve into the world of Javascript, I find myself grasping the concepts bit by bit. However, there's one thing that's been puzzling me, something so basic that I can't seem to find a clear answer on.

My challenge involves a sidebar with three small drop-down menus, each structured like this:

  <ul>
    <li>LEVEL 1
      <button class="sidebtn u1btn">
        <span class="material-icons-round">expand_more</span></button>
    </li>
      <ul class="u1">
        <li><a href="lessons?page=u1">the Weather</a></li>
        <li><a href="lessons?page=u2">Emotions</a></li>
        <li><a href="lessons?page=u3">the Family</a></li>
        <li><a href="lessons?page=u4">Food</a></li>
      </ul>
  </ul>

My goal is to have the arrow (the span element) flip when clicked. Initially, I tried the following solution:

$('.sidebtn').click(function () {
  $('div.sidebar button.sidebtn span.material-icons-round').toggleClass('flip');
});

However, this caused all three buttons with the .sidebtn class to flip, instead of just the one that was clicked. How can I target only the specific element that triggered the action, along with its child element (the span)?

I attempted to learn more about Javascript, but most of what I found was too advanced for my current knowledge level. I came across mentions of "event.target" but I'm unsure if that's the right approach. I tried the following without success:

function flipbtn() {
  event.target.firstChild.toggleClass('flip');

(I added onclick="flipbtn()" in the HTML.) My rationale was to toggle the "flip" class on the first child of the element that initiated the function, but I received an error stating "event.target.firstChild.toggleClass is not a function". I also experimented with:

const sidebtn = document.querySelectorAll('.sidebtn');

function flipbtn() {
  $(sidebtn).firstChild.toggleClass('flip');
}

However, the browser indicated that "$(....).firstChild is undefined". I also tried using "forEach" at one point, but that didn't yield the desired results, possibly due to incorrect implementation.

Understanding why these approaches failed would be enlightening, as I feel confident in my understanding of the objective and my logic behind the methods, even though they haven't worked. Nonetheless, any guidance on the correct approach would be immensely appreciated as I'm currently at a standstill.

Additionally, I aim to have each button open its respective drop-down menu. While I currently have a working solution by individually targeting each menu, I believe there must be a more efficient method. My current code for this task is:

$('.u1btn').click(function () {
  $('ul ul.u1').toggleClass('show');
});

$('.u2btn').click(function () {
  $('ul ul.u2').toggleClass('show');
});

$('.u3btn').click(function () {
  $('ul ul.u3').toggleClass('show');
});

There has to be a simpler way to achieve this. I could replicate the same strategy for the flip effect, but I'm confident that there's a more elegant solution that I'm overlooking. Thank you tremendously for your assistance.

Answer №1

If you're looking to implement the functionality using $(this).find, you can do it like this:

$('.sidebtn').click(function () {
    $(this).find('span.material-icons-round').toggleClass('flip');
});

For instance, you can toggle the class to change the color to blue:

$('.sidebtn').click(function () {
    $(this).find('span.material-icons-round').toggleClass('flip');
});
.material-icons-round.flip {
    color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>LEVEL 1
      <button class="sidebtn u1btn">
        <span class="material-icons-round">expand_more</span></button>
    </li>
      <ul class="u1">
        <li><a href="lessons?page=u1">the Weather</a></li>
        <li><a href="lessons?page=u2">Emotions</a></li>
        <li><a href="lessons?page=u3">the Family</a></li>
        <li><a href="lessons?page=u4">Food</a></li>
      </ul>
      <li>LEVEL 2
      <button class="sidebtn u1btn">
        <span class="material-icons-round">expand_more</span></button>
    </li>
      <ul class="u1">
        <li><a href="lessons?page=u1">the Weather</a></li>
        <li><a href="lessons?page=u2">Emotions</a></li>
        <li><a href="lessons?page=u3">the Family</a></li>
        <li><a href="lessons?page=u4">Food</a></li>
      </ul>
  </ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for reading JSON files in Rails with AJAX

I have implemented the following code snippets: #Inside timetable/new.html.erb <%= select_tag :department, options_for_select( @departments.collect{ |d| [d.department_name, d.id]}, nil),{ id: "department_select" } %> #Within timetable controlle ...

Is Selenium designed to work with standalone browsers (using webdrivers) or with browsers that are already installed on the operating system?

I am a newcomer to Cross Browser Testing and have just begun exploring Selenium. However, I am having trouble finding the answers to the following questions on the official site. It would be greatly appreciated if someone could help clarify them for me. ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

Difficulty in using a mouse click to transmit user data to the server

I'm struggling with creating an event that activates when the submit button is clicked. My objective is to execute the function Chat.send() using the input provided by the user in the text field at the top of the page when they press the "Send" button ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Updating the Bootstrap entry dynamically within the @NgModule module

My web application has a specific requirement where it can only be accessed through example.com/index.html without any parameters. The backstory behind this restriction is quite lengthy, so let's not delve into that. Within the index.html file, I have ...

New approach of using Django to replace Ajax method

My current input elements are: <input id="country_name" type"text" /> <input id="country_id" type"text" /> I am looking to dynamically update the ID based on the country name entered in the country_name input using the onchange event. To achi ...

Using the conditional rendering technique in a mapped function within a React table cell

I have an array that is being displayed inside a Table, and I need to compare each object's "userName" property with the header in order to determine where to place the value. If there is no match, it should display a "0". Here is a snippet of the ta ...

__dirname value not able to be retrieved

Currently, I'm utilizing __dirname to obtain the absolute path to the GraphQL schema: const schema = loadSchemaSync(path.join(__dirname, './graphql/schemas/schema.graphql'), { loaders: [new GraphQLFileLoader()] }); After transitioning the ...

Exchange selection choices among harvested selected boxes

In my project, I am working on swapping all the options between two select boxes. The specific scenario I am dealing with involves recording details of phone calls. These calls can either be inbound or outbound. For outbound calls, I have a 'caller&ap ...

Strategies for Structuring Django and JavaScript Codebases

I'm grappling with the best way to structure my javascript and django code. Previously, I would include my page-specific javascript directly in the template file within a <script> tag. However, as my javascript code grew, this approach led to a ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Retrieving two sets of AJAX data at the same time

Recently, I've encountered a challenge with filling in data from a MySQL server via PHP into two tables in my HTML. As someone new to website development, I might not be articulating the issue correctly. In my HTML, I've included my external .js ...

The domain name or IP address does not correspond to the alternate names listed on the certificate

I am currently facing an issue with installing npm packages in my react native project. Every attempt to install a package from npm results in the error message shown below: fitz:tesseractOcrSample fitzmode$ npm i npm ERR! request to https://registry.npmj ...

Updating a component with React JS setState() must be done on a mounted or mounting component

I encountered an issue where I am getting the error message setState(...): Can only update a mounted or mounting component., but I am struggling to find a solution. import React, { Component } from 'react'; import Loading1 from '../images/ ...

Can different versions of Node be used simultaneously for various Node scripts?

Currently, I am utilizing nvm. Can a specific node version be used for a particular script? For instance... Using node 6 forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js U ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...