Using Jquery to select and apply functions to specified div elements

As someone who is relatively new to JQuery, I have a question regarding the .on() function. Take this example:

$('div').on('click', function() {$(this).toggleClass('show-description');});

This code selects all the 'div' elements in my HTML file and listens for a click event. When clicked, it will toggle the 'show-description' class on and off for the last div that was clicked on.

<div class="show-description"> ......</div>

Now, what if I only want to target a specific class within a div tag for my event listener?

I attempted the following:

$('div.about').on('click', function() {$(this).toggleClass('show-description');});

In my HTML, it looks like this:

<body>
 <div class="clearfix"> 
  <div class="column">
    <ul>
     <li id='about'> <span>About Me</span> </li>
      ......
   </div>
 </div>

However, my 'show-description' styles don't seem to be triggering. I've done some research on the .on() method from the API documentation and checked Stack Overflow, but I'm still stuck. I'm not expecting a direct solution, just hoping for a helpful nudge in the right direction.

Thank you.

Answer №1

$('div.about') will target all div elements with the class about. Interestingly, in your specific case, none of the div elements possess this class.

In the provided example, you do have an element with the identifier about, which is not a class but rather an id, and it exists within the li element.

If you are looking to interact with this element, you may want to use: $('li#about').on('click', ...

Take a look at the following code snippet:

$('div.about').on('click', function() {$(this).toggleClass('show-description');});


$('li#about').on('click', function() {$(this).toggleClass('show-description');});
.show-description {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clearfix"> 
  <div class="column">
    <ul>
      <li id='about'> <span>About Me</span> </li>
    </ul>
  </div>
  <div class="about">This div has the "about" class</div>
</div>

In the above example, there are two clickable elements - li#about and div.about. Clicking on either will toggle a red border on the clicked element.

Additionally, for the given example, we could achieve the same functionality using

$('div.about, li#about').on('click', ...

Answer №2

Is it possible to target a specific class that I defined within a div element to handle an event?

In the illustration below, I'm not using the class and on functions, but you should be able to grasp the concept. Imagine you have the following HTML code:

<ul class="topnav">
  <li>Item 1</li>
  <li>Item 2
    <ul>
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

If you want to apply some changes to every li inside a ul, you can use this line of code:

$( "ul.topnav li" ).css( "border", "3px double red" );

However, if you only want to target the direct child li elements inside and immediate children of the ul, you can use something like this:

$( "ul.topnav > li" ).css( "border", "3px double red" );

For your particular scenario, you could try something like this:

$( "div #about" ).on( ... );

I hope this explanation is useful.

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

Retrieving Data from Database on the Current Page

Struggling with fetching data from a MySQL database using PHP search methods and displaying the results on the same page? Here's how you can achieve it. This HTML Script: <html> <head> <title>Digital Library</title> </head ...

I am utilizing the ternary operator within the map function to dynamically adjust the column width of a material table

Looking to adjust column widths based on the IDs received from the map function. Check out the code snippet: <TableRow> { tableData.header.map(header => { header.i ...

Interactive dropdown menu with options for different actions

They say a picture is worth a thousand words. I have an idea for a feature I want to add to my Django web application: I want to create a dynamic dropdown list that allows users to add values to the database and dynamically updates itself with the new sel ...

Revamping CSS for a Responsive Wordpress Tesseract Theme

I'm currently in the process of developing a website using the Tesseract theme at thevandreasproject.com. However, I have encountered an issue with responsiveness when integrating the SiteOrigins PageBuilder plugin. The compatibility between PageBuild ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...

How can we identify if the user is utilizing a text-input control?

Incorporating keyboard shortcuts into my HTML + GWT application is a goal of mine, but I am hesitant about triggering actions when users are typing in a text area or utilizing the keyboard for select menu operations. I am curious if there exists a method ...

Splitting HTML content into nodes using PHP XPath (including empty nodes)

I am currently attempting to separate the HTML string into individual nodes, along with their text content if applicable. Here is the HTML string that I am working with: <p>Paragraph one.</p> <p><strong>Paragraph <em>two</ ...

How to line up two blocks side by side in a single block with Bootstrap without the use of CSS

The bootstrap margin is causing issues with this code <div class="row"> <div class="row1 col-lg-3"> <div class="row2 col-lg-1"></div> <div class="row2 col-lg-1"></di ...

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...

How to turn off validation for md-input-container in Angular 2

While working on a form in Angular 2, I encountered an issue when adding the required attribute to my <input>. The problem resulted in unwanted margins as shown in this image: I am seeking a solution to only apply the second red margin to the input ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

Is JSF h:outputStylesheet converter the solution for creating dynamic CSS?

Recently, I came across the <h:outputStylesheet/> tag with a converter attribute. I tried attaching a dummy (pass-through) converter to it, but to my surprise, nothing happened. Upon further investigation, it appears that the converter is not even in ...

Uncheck the previous option selected in a multi-select dropdown using jQuery

Hey there, I've been facing an issue with my change handler when trying to add or remove values from an Array. It works fine until the last element is selected, at which point the change event does not fire properly. Has anyone else encountered this p ...

Ways to transition to an iframe window

I am having difficulty selecting an iframe popup window as it is not coming into focus. Below is the image of the popup window along with the button I am attempting to click: https://i.stack.imgur.com/VzkOX.png This is the code snippet that I have been ...

Nesting CSS classes allows for more specific targeting of

I am a bit rusty on CSS, it's been about 5-7 years since I last worked with it. Could someone help me come up with a solution to my problem? Here's the ideal design I have in mind: table.ctable { class:collapsible collapsed; } I know this syn ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

What is the best way to collapse the entire navigation menu after clicking a link (nav-link) within it?

I created a navigation menu using HTML and SCSS, but I'm facing an issue where the menu does not close when clicking on links inside it. The menu continues to overlay the content on the page instead of closing. Essentially, I want the navigation menu ...

Exploring Javascript parameters with the power of jquery

Is it possible to pass a parameter from PHP into a JavaScript function within HTML? I am currently facing an issue where my code crashes when it reaches a certain condition. This is the code snippet causing the problem: $str="<input type='submit&a ...

Horizontal JQuery Slider for CategoriesDiscover the smooth, sleek category navigation with

Looking to create a sliding horizontal menu with various categories using a clever div layer setup. The goal is to have one fixed-width div containing another wider div, with only a portion of the second one visible at a time. Encountering two challenges ...

Ways to trigger the onclick event from different controls

I have a videojs player and a button on my html page. The videojs player supports the functionality to pause/play the video when clicked. I want to trigger this event by clicking on my button. How can I achieve this? Here is the code that I tried, but it ...