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

Is it possible to modify the text displayed under your website when you search for it online?

I recently developed a website using HTML, CSS, and Javascript. Whenever I search for it on the internet, there is always a text paragraph displayed below its name in the search results. A similar example can be seen in the image here for Facebook. Is th ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

The spacing problem arises from the interaction between two HTML tags containing a Bootstrap file

view image details hereUsing Bootstrap 5, I have a screenshot with an h5 element in a black border and an em tag in a red border. I specified margin 0 to the h5 element but it still does not touch the em tag (in red border). I have tried adjusting line spa ...

What is the proper way to define a class attribute for an HTML element within a PHP file?

I am having trouble writing the class attribute in a PHP file for an HTML element. Here is my code: echo '<div><p class="'.($value->getIsRequire() == 1) ? 'required' : ''.'"> </p> <input type="tex ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Guide on incorporating a JS file in a React application

I recently obtained a template for my website that includes the following JS file which is being called from my React component. !(function($) { "use strict"; // Hero typed if ($('.typed').length) { var typed_strings = $(&quo ...

Is there a way to eliminate the gap between my menu choices?

Is there a way to eliminate the black line that appears between my menu options when using CSS hover? https://jsfiddle.net/jameskelly/3ejsu7gx/2/ a:hover { background-color: #ebebeb; font-color: black; } /* Custom styling for the ...

Why is it that an HTML entity-containing string doesn't show the character after going through the htmlspecialchars() function?

In my project, I have a string of text retrieved from the SQL database which is then sanitized using PHP's strip_tags and htmlspecialchars functions to eliminate any HTML formatting that users might try to inject. This processed text is displayed in b ...

A modern alternative to using the outdated `confirm` method in

I am exploring ways to prompt the user before allowing them to save a record. Let's say I have this button defined in the markup: <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click"></asp:Button> ...

The v-autocomplete feature in vuetify doesn't allow for editing the text input after an option has been selected

Link to code on CodePen: CodePen Link When you visit the provided page and enter "joe" into the search box, choose one of the two Joes that appear. Try to then select text in the search box or use backspace to delete only the last character. You will no ...

What is the best way to ensure that when a div is opened, the information to the right does not get pushed down?

I have a functioning menu bar, but when it expands, the content below is pushed down even though it should not be affected. How can I adjust my code to prevent this issue? View my website here: <div id="menu_wrapper"> <div id="menu"> &l ...

Changing characters to asterisks using Javascript

I am currently working on a function that transforms all characters after the first word into asterisks. For example, if I have MYFIRSTWORD MYSECONDWORD, I would like it to show as: MYFIRSTWORD *** Currently, I'm using the code below which replaces ...

Problem with Ajax functionality on Jquery Dialog

I have implemented a Jquery.dialog feature in my application for sending messages. When the user clicks on "new", the dialog box appears, allowing them to select the recipient (currently working with IDs instead of usernames). On the first opening of the ...

Guide to implementing a seamless Vue collapse animation with the v-if directive

Struggling with Vue transitions, I am attempting to smoothly show/hide content using v-if. Although I grasp the CSS classes and transitions involved, making the content appear 'smoothly' using techniques like opacity or translation, once the anim ...

choose a CSS class within a div element's class name

Hey there, I'm dealing with two HTML divs that both have the same price class of "uvp uvp-price". <div class="product-detail-price-container"> <meta itemprop="price" content="119.8"> ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

Issue with React router not functioning correctly when dealing with dynamically created anchor tags utilizing jquery

As a newcomer to React.js, I have incorporated jQuery into my project to handle mouse and click events for cloning navigation elements, specifically <li> tags within <a> tags. The cloned elements are displayed in a targeted div ID successfully. ...

What is the best way to resize an image in HTML based on a percentage of its height?

Within my HTML code, I have a PNG image that has been adjusted in size using CSS: .adjust-image { border:1px solid #021a40; display: block; width: auto; max-width: 100%; max-height: 1000px; } .img-container { position: relative; } ...

My website using Dynamic Ajax technology is currently experiencing heavy traffic due to the number of getScript

I am facing an issue with my dynamic website where all links fetch new sections via ajax requests from other pages and replace the current section. The problem I encounter has two main aspects. When loading a new div from an Ajax get request, some sections ...

Leveraging strings as URLs to embed PDFs in Wordpress using PDF Embedder

I'm encountering an issue related to a Wordpress plugin called PDF Embedder, as well as concatenating/using a string with document.write. My goal is to make this code work: <script src="http://nooze.org/wp-content/uploads/scripts/dateGetter.js"> ...