Javascript target all classes

Javascript target all classes

You can pass as many classes to the add() method as necessary.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); >);

If any of the classes are already present on the element, they won’t get added a second time.

Similarly, if you need to remove one or more classes, you can use the remove() method.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); event.target.classList.remove( 'second-class', 'third-class' ); >);

If any of the classes are not present on the element, they get ignored.

# Add class to selected Elements on click

To add a class to selected elements on click:

  1. Select a group of elements using the document.querySelectorAll() method.
  2. Use a for. of loop to iterate over the collection.
  3. On each iteration, add a click event listener to the element that adds a specific class.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> style> .bg-yellow background-color: yellow; > style> head> body> div class="box1">Box 1div> div class="box2">Box 2div> div class="box3">Box 3div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) box.addEventListener('click', function handleClick() box.classList.add('bg-yellow'); >); >

We used the document.querySelectorAll method to select the DOM elements with classes box1 , box2 and box3 .

We used the for. of loop to iterate over the collection of elements and added a click event handler to each element.

We used the add() method to add a class to the clicked element.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

John swana

Workarounds «loops»
Loops can mess up your code I personally don’t like them.
To target all elements you will have to iterate through all of them for each element you will have to add a event listener

Example
For instance the are 3 links of a same class and you want to add event listeners on all of them
.
.
.
// JavaScript
const links = document.getByClassName(«links»)
for(var i = 0; i < links.length; i++)
links[i].addEventListener(‘click’, event => console.log(event.target.get attribute(‘class’)))

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Comments

Post a Comment

How to install Kotlin programming language

Kotlin is a programming language that is statically typed runs on the JVM and can compile to JavaScript To install kotlin using the Software Development Kit on Debian Ubuntu or Linux environment. First install the SDK using Command: wget -O sdk.install.sh «https://get.sdkman.io» bash sdk.install.sh To install kotlin Type the command: source ~/.sdkman/bin/sdkman-init.sh sdk install kotlin To install Java development kit (JDK) a vital dependency used for execution and compilation of kotlin code. Type the command: sudo apt-get install openjdk-8-jre-headless To confirm installation type the command: kotlin -version It should return output similar to one below Kotlin version 1.3.61-release-180 (JRE 1.8. )

How to write a self invoked function in JavaScript

Self invoked functions are function that run on themselves without need to be called, the syntax to create self invoked functions is as follows; (function()< // function body >)() the runtime will run everything in a self invoked function’s body You can pass parameters to the function using the syntax below; (function(params)< // function body >)(params) parameters will be made available to the function as any other argument

How to set content disposition header for nginx server to force content download

Nginx (pronounced as engine x) is an HTTP server, reverse proxy server, as well as a mail proxy server Nginx is well known for its high performance, stability, efficiency, rich feature set, simple configuration, and low resource consumption. content disposition headers direct web browsers to save content instead of attempting to render it To set content disposition open your desired server configuration in «/etc/nginx/sites-available/» within your configuration add code below within your server location ~* (mp3|ogg|wav)$ < add_header Content-Disposition "attachment"; >mp3, ogg and wav are example file extensions matched by regular expressions rules Test configuration by acessing mp3, ogg and wav files from your webserver Alternatively you can force custom filenames as shown below «$1» substitutes filenames sent to clients. As an example its value corresponds to the requested file’s extension lo

How to create zip archives in nodejs

I’m going to compile ways in which you can create archives compressed using zip algorithm in nodejs or a similar JavaScript runtime. node-zip is an open source zip archiving utility authord by daraosn and folked from jszip capable of compresding files into a zip archive and extracting zip archives in JavaScript. node-zip is available on npm you can install it in your terminal window by typing; npm install node-zip example usage const zip = new require(‘node-zip’)() zip.file(‘test.file’, ‘John Swana’) const data = zip.generate() console.log(data) How to unzip a zip archive const zip = new require(‘node-zip’)(data, ) console.log(zip.files[‘test.file’])

Reasons why you shouldn’t consider hosting on github pages

Image

Github pages is a service for deployment of static websites normally software documentation and blogs Github pages is available on all public github repositories and on premium accounts it extends to private repositories as well. So what’s not to like about it. hmmmm think about it. that’s too good to be true It’s not a secret that «the only free cheese is served on a mouse trap» 1. «Downtime due to maintenance» Every now and then github pages websites undergo an annoying and imaginary maintenance that causes undesirable user experience especially for professional websites. 2. «Slow deployment» I’ve been using github pages to host my static website with less than 10,000 pages deployment process knocked my entire site offline for 10 mins again that’s unnecessary downtime sometimes it extended to days 3. «uninvited cloners» So you put your site out there few days later 50 clones uninvited unwelcom

Источник

How to target all elements with a specific class in JavaScript

I’m currently working with WordPress and Bootstrap 5.

Due to WordPress limitations with the wp_nav_men function. I can’t see the markup at all. This means I can’t manually added classes here and there. I need to do this in order to get the Bootstrap sub menu navs to work. This means I need to use JavaScript to inject specific things to certain elements to

For me to achieve this, it would seem I need to get additional child nodes with the same class names to inherit the same JavaScript settings. Here’s what I am trying to do. Below I have listed what I see in the markup, the steps I would like to see happen, and what the JavaScript looks like currently.

STEP 1:
If any li with a class of .menu-item-has-children , add the following id , role , data-bs-toggle and class to the element.

STEP 2:
Any li with a with a class of .menu-item-has-children also with a ul will have a sub nav menu. Because of this, the sub nav menu must inherit the following class of dropdown-menu .

 // Toggle child menu item in main nav // assign expanse li to variable let liExpanse = document.querySelector('.menu-item-has-children'); // check if nested ul is contained in parent li of main nav let liExpanseChild = document.querySelector('.sub-menu'); // add id, role, data attributes to div function addAtt() < liExpanse.firstChild.setAttribute('id','dropdownMenuLink'); liExpanse.firstChild.setAttribute('role','button'); liExpanse.firstChild.setAttribute('data-bs-toggle','dropdown'); >addAtt(); // add classnames to divs function addClassName() < liExpanse.firstChild.classList.add('nav-link', 'dropdown-toggle'); liExpanseChild.classList.add('dropdown-menu'); >addClassName(); 

THOUGHTS:
I do notice that when using firstChild methods, it only looks for the first child. There is also a lastChild option, but what I am looking for is to find all nodes with a class of .menu-item-has-children , then do the following.

With some research and based on comments, I actually don’t want the querySelectorAll to pick up on all that is related to that class or ID. Just the one level.

Solution

Top-level elements will have .menu as their parent. You could also use #mainNav in its place. In css > means thing on the left is a direct parent of thing on the right.

document.querySelectorAll(".menu > .menu-item-has-children > a") 

Top-level submenu selector

document.querySelectorAll(".menu > .menu-item-has-children > .sub-menu") 

Using the id of the parent instead of the class, if its more convenient

document.querySelectorAll("#mainNav > .menu-item-has-children > .sub-menu") 

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Источник

Javascript target all classes

You can pass as many classes to the add() method as necessary.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); >);

If any of the classes are already present on the element, they won’t get added a second time.

Similarly, if you need to remove one or more classes, you can use the remove() method.

Copied!
document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); event.target.classList.remove( 'second-class', 'third-class' ); >);

If any of the classes are not present on the element, they get ignored.

# Add class to selected Elements on click

To add a class to selected elements on click:

  1. Select a group of elements using the document.querySelectorAll() method.
  2. Use a for. of loop to iterate over the collection.
  3. On each iteration, add a click event listener to the element that adds a specific class.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> style> .bg-yellow background-color: yellow; > style> head> body> div class="box1">Box 1div> div class="box2">Box 2div> div class="box3">Box 3div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) box.addEventListener('click', function handleClick() box.classList.add('bg-yellow'); >); >

We used the document.querySelectorAll method to select the DOM elements with classes box1 , box2 and box3 .

We used the for. of loop to iterate over the collection of elements and added a click event handler to each element.

We used the add() method to add a class to the clicked element.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Меняем цвет шрифта при помощи HTML
Оцените статью