Tips for including a class using selector chaining in JavaScript

I am facing an issue where I need to add a class to a group of <a> tags. I tried using the querySelectorAll method to select all the a tags, but for some reason, the class is not being added to them.

Here is the code snippet that I have tried:

var qc=document.querySelectorAll(".Label ul li a");
qc.className+="newcls";

You can see the result in this JSFiddle link.

Although I managed to achieve it using jQuery, I want to avoid using jQuery and find a solution using plain JavaScript.

document.addEventListener("DOMContentLoaded", function() {
   var elements = document.querySelectorAll(".Label ul li a");
   elements.forEach(function(element) {
       element.classList.add("newcls");
   });
});

Answer №1

Here is a recommended solution:

// Converting the elements collection fetched from
// document.querySelectorAll() into an Array using
// Array.from(), and then iterating over that array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll(".Label ul li a") ).forEach(

  // Utilizing arrow function syntax to execute the same
  // action on each <a> ('aElement') within the
  // array; in this case, using Element.classList API to
  // append the specified class name:
  aElement => aElement.classList.add('newClass')
);

Answer №2

To go through the Collection, you can try this method:

var elements = document.querySelectorAll(".Label ul li a");
[].forEach.call(elements, function(element) {
    element.className+=" newclass";
})

Check out the updated Fiddle here

Don't forget to include a space before the class if using className, as you are modifying the entire class. Alternatively, you can use

element.classList.add('newclass');

Answer №3

Ensure you iterate through the collection in your code where qc represents a collection of elements. It's important to note that className is not a collection but rather a string containing class names separated by spaces.

var qc=document.querySelectorAll(".Label ul li a");
for(var i=0; i<qc.length; i++) {
    qc.classList.add("newcls");
    //consider using the following line for compatibility with IE versions prior to 10
    //qc.item(i).className+=" newcls";
}

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

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

Is there a way to perform reverse geocoding using the Google Maps API?

Currently, I have incorporated the following code into my website to showcase google maps along with autocomplete functionality. My ultimate goal is to enable reverse geocoding using longitude and latitude coordinates and exhibit the corresponding address ...

Personalized Element Commands and features

UniquePage.html <div ng-controller="UniquePageCtrl"> <unique-custom-directive arg1="{{currentObj.name}}"></my-custom-directive> <div> in UniquePageCtrl.js (Controller) app.controller("UniquePageCtrl", ["$scope", function ($sc ...

Vue: unable to switch to a different page

I am a newcomer to Vue and I have successfully created a dynamic page that fetches questions, user names, and categories from an API. Everything is displaying correctly, but I am facing an issue with making certain elements clickable. Specifically, I want ...

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

The attempt to test the AngularJS application using the Jasmine plugin was unsuccessful

I'm currently in the process of learning how to write test cases for my angularJS application. As a beginner, I'm searching for some sample examples of working demos. I came across an example online that uses the Jasmine plugin to test an angular ...

The error message "npm ERR! enoent" indicates that npm is unable to locate a specific file

How do I troubleshoot this issue? After attempting the master version, I encountered a similar error. My operating system is OSX Yosemite: bash-3.2$ yo meanjs You're utilizing the official MEAN.JS generator. ? Which version of mean.js would you like ...

What is the process for importing a submodule in webpack?

I've set up a React component in an npm package called 'share-sheet'. This component is managed by webpack with the following configuration: webpack.config.js ... output: { path: path.join(__dirname, '/dist'), filename: & ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Rails - removing list item upon deletion of parent object

Currently working on a project app as part of a full stack developer bootcamp program. One of the features I'm implementing is a destroy method to remove an item from a list. Using AJAX requests, the goal is to dynamically remove the li element repres ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Reveal/Conceal footer upon vertical scrolling

I am attempting to achieve the following goals: Display the div element when the scrolling position is greater than 20 Apply a fadeOut effect after a certain delay Prevent the fadeOut effect when hovering over the sticky footer This is my implementation ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

What could be causing my HTML to not display properly after making changes to a text node?

Can a DOM text node be altered in such a way: node.nodeValue = "foo <strong> bar </strong>" so that it displays the HTML correctly? Appreciate any help. ...

The PHP file is returning a 403 Forbidden error for specific requests

My PHP script is returning a 403-Access Forbidden error for some HTTP requests, while others are working fine. I am receiving a 403 error for the following request (via AJAX) POST http://example.com/api/interaction/practitioner HTTP/1.1 Host: example.co ...

How can I submit a form or retrieve HTML content using JavaScript without using an iframe?

Background: My current job involves transcribing paper reports using a webapp that is quite old and cannot be updated or connected to a database directly. The system only checks for duplicate unique IDs once the entire form is submitted. This often leads ...

What sets asyncData apart from methods in Nuxt.js?

I am currently utilizing asyncData to fetch data from an API, however it is restricted to pages and cannot be used in components. On the other hand, methods can be used in both pages and components. As these two methods function similarly, I am consider ...

Omit node_modules from typescript compilation using gulp-typescript

Having trouble running a gulp task to compile my typescript due to dependency-related errors. /content/node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'. /content/node_modules/@angular/core/src/facade/l ...

Two jQuery event handlers with similar functionality are displaying distinct behaviors

I've encountered an issue with two identical document fragment objects where separate event listeners are attached using jQuery, as demonstrated in this fiddle. Although the two event listeners should function the same way, only the first one behaves ...