Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links).

I've tried various methods, but the current jQuery method I'm using adds the class to all links every time one is clicked, which is not the desired behavior.

Should I assign a unique class or ID to each link and target them individually with JavaScript/jQuery, or is there an easier way to achieve this?

<nav>
    <ul>
        <li>
            <a href="#HOME">HOME</a>
        </li>
        <li>
            <a href="#ABOUT">ABOUT US</a>
        </li>
        <li>
            <a href="#SERVICES">SERVICES</a>
        </li>
        <li>
            <a href="#TEAM">TEAM</a>
        </li>
        <li>
            <a href="#PORTFOLIO">PORTFOLIO</a>
        </li>
        <li>
            <a href="#PRICING">PRICING</a>
        </li>
        <li>
            <a href="#BLOG">BLOG</a>
        </li>
        <li>
            <a href="#CONTACT">CONTACT</a>
        </li>
    </ul>
</nav>

<script>
$('li').click(function(){
$(this).find('a').addClass('links');
});

</script>

Answer №1

Focus on only the anchor element within the clicked list item

$('li').click(function(){
    $(this).find('a').addClass('links');
});

To also remove the class from other anchors

$('li').click(function(){
    var currentAnchor = $(this).find('a').addClass('links');
    $('li a').not(currentAnchor).removeClass('links');
});

Answer №2

If you're looking to target your DOM children using jQuery, the children() API is a helpful tool to use.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
    <ul>
        <li>
            <a href="#HOME">HOME</a>
        </li>
        <li>
            <a href="#ABOUT">ABOUT US</a>
        </li>
        <li>
            <a href="#SERVICES">SERVICES</a>
        </li>
        <li>
            <a href="#TEAM">TEAM</a>
        </li>
        <li>
            <a href="#PORTFOLIO">PORTFOLIO</a>
        </li>
        <li>
            <a href="#PRICING">PRICING</a>
        </li>
        <li>
           <a href="#BLOG">BLOG</a>
       </li>
       <li>
           <a href="#CONTACT">CONTACT</a>
       </li>
   </ul>
</nav>

<script>
$('li').click(function(){
    $('a').removeClass('links');
    $(this).children().addClass('links');
});

</script>

Answer №3

Kindly review the enclosed code snippet below which may provide a solution to your query.

$('li').click(function(){
  $('li').not(this).each(function(index, li) {
    var anchor = $(li).find('a:first'); 
    anchor.removeClass('link');
   });
   $(this).find('a:first').addClass('link');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
    <ul>
        <li>
            <a href="#HOME">HOME</a>
        </li>
        <li>
            <a href="#ABOUT">ABOUT US</a>
        </li>
        <li>
            <a href="#SERVICES">SERVICES</a>
        </li>
        <li>
            <a href="#TEAM">TEAM</a>
        </li>
        <li>
            <a href="#PORTFOLIO">PORTFOLIO</a>
        </li>
        <li>
            <a href="#PRICING">PRICING</a>
        </li>
        <li>
            <a href="#BLOG">BLOG</a>
        </li>
        <li>
            <a href="#CONTACT">CONTACT</a>
        </li>
    </ul>
</nav>

Answer №4

Try utilizing the this selector when working with jQuery.

<script>
   $('nav ul li').click(function(){
   $('nav ul li a').removeClass('links');
   $(this).find('a').addClass('links');
   });
</script>

Answer №5

Check out this cool jQuery code snippet:

$("a").click(function(){
        $(this).addClass("links");
        $("a").not($(this)).removeClass("links");
    });
    

Answer №6

Give this a shot!

$('li').on('click', function() {
  $('.choose').removeClass('.choose');
  $(this).find('a').addClass('choose');
})

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

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

Navigating the world of gtag and google_tag_manager: untangling

Tracking custom events in my react application using Google Analytics has been successful. Initially, I followed a helpful document recommending the use of the gtag method over the ga method for logging calls. The implementation through Google Tag Manager ...

Incorporating images with JavaScript in Jade templates

Currently I have a layout.jade code that I am looking to modify the javascript for. My goal is to load an image onto the page every time it is reloaded using jade. Here is the existing code: html head title= title script(src='/libs/jquery/j ...

Set the status to 0 when the user exits the browser

I am currently working on developing a straightforward system to indicate whether the user is online or not. However, I have encountered a specific issue. Once the user closes the tab or the browser, the ajax code fails to refresh the page that tracks use ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

If you don't get the correct response from the $.ajax success function

I am utilizing the $.ajax function to retrieve content, however I am encountering an issue when attempting to display special tags from it. The data appears to be missing! This is how I am currently handling it: $(document).ready(function(){ $("button") ...

The webpage loaded through ajax is not rendering correctly

One of the challenges I'm facing is getting a JavaScript script to load an HTML page into a specific div element on another HTML page: The page that's being loaded, startScreen.html, looks like this: <!DOCTYPE html> <html lang="en ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

Understanding the process of retrieving the value of an element produced in a PHP foreach loop

I am faced with an issue in my code where elements are being generated within a for loop using PHP. Here is the snippet of the code: for($i=0; $i < $count; $i++) { $member = $my_array[$i]; <td><span id="myspan"><input type="text" id= ...

What is a more effective way to showcase tab content than using an iframe?

I currently have a webpage set up with three tabs and an iframe that displays the content of the tab clicked. The source code for each tab's content is stored in separate HTML and CSS files. However, I've noticed that when a tab is clicked, the ...

Utilizing asynchronous operations in MongoDB with the help of Express

Creating a mobile application utilizing MongoDB and express.js with the Node.js MongoDB driver (opting for this driver over Mongoose for enhanced performance). I am aiming to incorporate asynchronous functions as a more sophisticated solution for handling ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Utilize the ng-click feature for swiping interactions in Ionic v1

I have a slide page on Ionic V1 that utilizes previous and next buttons. Here is an example: <button id="" class="button button-slide prev no-animation" ng-click="prev()" ng-show="activeIndex > 0" > BACK </button> While the click function ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...

Check for blur function support in jQuery for Chrome and Safari browsers

Is there a way to detect when a file upload input field has been updated in different browsers? In IE & FF, the blur() method can be used for this purpose, while in Chrome change() is required. Since Chrome (and possibly safari) do not trigger the blu ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...