Choosing the child anchor element within a list item

Having trouble selecting the anchor link in the DOM that is a direct child of my list item "dropdown-nav". I want it to change when the list item is clicked, but it's not working. The active class is being applied correctly. What could be the issue here?

var acc = document.getElementsByClassName("dropdown-nav");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active-hit");
    this.find("a").attr("href", "http://www.google.com/");
  });
}
<ul>
  <li class="dropdown-nav">
    <a href="/about">About
      <span class="nav-desc">Our company</span>
    </a>
    <div class="hide-border"></div>
    <ul class="second-tier">
      <div class="hide-corner"></div>
      <li><a href="#">Our Mission</a></li>
      <li><a href="#">Our People</a></li>
      <li><a href="#">Work with us</a></li>
      <li><a href="#">High Value Manufacturing</a></li>
    </ul>
  </li>
</ul>

Answer №1

By incorporating jQuery into your code, you can streamline it by utilizing jQuery functions like so:

$(".dropdown-nav").click(function() {
  $(this).toggleClass('active-hit');
  $(this).find('a').attr("href", "http://www.google.com/");
})
.active-hit {
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="dropdown-nav">
    <a href="/about">About
      <span class="nav-desc">Our company</span>
    </a>
    <div class="hide-border"></div>
    <ul class="second-tier">
      <div class="hide-corner"></div>
      <li><a href="#">Our Mission</a></li>
      <li><a href="#">Our People</a></li>
      <li><a href="#">Work with us</a></li>
      <li><a href="#">High Value Manufacturing</a></li>
    </ul>
  </li>
</ul>

Answer №2

this is not a jQuery object. Here's how you can update the href attribute of the first link:

this.getElementsByTagName('a')[0].setAttribute('href', 'http://www.google.com/');

If you have jQuery included, you can also achieve the same result with this code:

$(this).find("a").attr("href", "http://www.google.com/");

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

Navigation bar limited to text links only

I've checked out similar inquiries, but I couldn't find a solution that fits my situation. I'm looking to make the boxes around each text link clickable, as opposed to just the text itself. HTML <div class="container"> <ul cla ...

Implementing a personalized surcharge for a specific choice during the checkout process in WooCommerce

Within the WooCommerce Checkout page, a dropdown custom field for "Card type" has been incorporated with various options. Some of these options are free while others have an associated fee of $0.99. Although the fee is accurately calculated on the checkout ...

The "getJson" function fails to execute when attempting to run a Python

I've come across a simple code snippet, but for some reason, my getjson function isn't working as expected. My Python script properly prints a JSON encoded value. Does anyone have any suggestions? HTML <!DOCTYPE html> <html> <h ...

Loading Pages Dynamically with Ajax and jQuery

I'm a jQuery newbie and I'm interested in learning about the method that allows loading content with domain.com/#/this using Ajax when clicking a link. It's similar to how http://cargocollective.com/#/featuredprojects works. This also occurs ...

When running the command "npm start," an error occurs stating: Plugin/Preset files are prohibited from exporting objects and can only export functions

I recently started using reactJS and was following a tutorial. However, I encountered an error when trying to run "npm start". Here is the error message: ERROR in ./main.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Plugin ...

Using Node.js's `createReadStream` function in the context of functional

I am seeking feedback on the utilization of TaskEither with fp-ts or another functional programming library for educational purposes: When working with a nodejs stream, I currently use a Promise. Is this an effective approach, and are there simpler alt ...

Applying 100% height to a div element for positioning

I would like to achieve the following layout: The navigation should be fixed at the top, and the height of the div with the background image should be 100%. I want to place content below the image. My issue is that when I set the positioning of the image ...

Embedding complex JSON information into an HTML dropdown menu

Here is a JSON string that I am working with: { "electronics": { "cameras": [ "sony", "nikon", "canon" ], "TV": "none", "laptop": [ "hp", "apple", "sony" ] }, "home": { "furniture": [ ...

What is causing columns.render not to trigger when DataTable().draw() is invoked?

I'm wondering why the columns.render method is not part of the execution flow when using DataTable().draw(). For instance: HTML <table id="data"> <thead> <tr> <th>TimeColumn</th> < ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

generate a cookie within a pop-up window

Can someone help me figure out why my Modal Window with a cookie to display only once isn't working? I followed this tutorial at . Here is the link to my website: Here is my code: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" a ...

Exploring the utilization of server-side Web Sockets functionality

Recently, I've been diving into the world of Web Sockets and I'm eager to understand how server-side implementation works. While I feel comfortable with writing client-side code using onmessage() in HTML5, JavaScript, etc., I find myself unsure a ...

Steps to trigger an AngularJS modal window when the URL contains a query string

I am in the process of creating a website and I would like to have a $uiModal open when there is a querystring in the URL. If there is no query string, then the modal should not open. Here is the code snippet: myApp.controller('jobObjectiveController ...

Tips for choosing an SVG element within an HTML <object> tag using JavaScript

I have an Angular application where I need to select the embedded SVG element within an <object> tag using JavaScript or Angular jqLite. Usually, in order to accomplish this task, one typically needs to write code similar to the following: // Creat ...

Stop users from entering a value higher than the one already inputted

Is there a way to prevent users from inputting values larger than totalofservices for totalontarget and totalofftarget? <script> $(document).ready(function() { $('.totalofservices').keyup(function(){ var totalOfServices = pa ...

Exploring JavaScript's usage of the var keyword within loops versus outside loops

Recently, my coworker and I engaged in a discussion about the best and worst practices when it comes to using the var keyword within loops. Here is my approach: for (var i = 0; i < anArray.length; i++) { for (var j = 0; j < anotherArray.length; ...

The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here My code successfully shows and hides the navigation items, but it's not updating the burger icon No console errors or warnings are present This is my HTML: <nav> ...

In the process of protecting a comment form and its corresponding API endpoint, it's important to consider where input should be sanitized, validated, and encoded - whether that

I am currently working on enhancing the security of a comment form in a non-CMS environment without user authentication. The goal is to protect the form from both browser and curl/postman type requests. Environment Backend - Node.js, MongoDB Atlas, and ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

"Dynamically design a responsive mobile menu for Genesis Child Theme in Wordpress with full height

I'm in the process of designing a website for my sisters' band and I'm struggling to develop a mobile menu with full width and height in Wordpress (using PHP). The theme being used is Genesis. Can anyone provide assistance with this? Feel fr ...