find all elements add class jquery

this will grab all a elements, and dump them to the console.

var allLinkElements = $( "a" ); console.log(allLinkElements);

then we need to split into a jquery object, this is a jquery version of an array. tell it to look in a certain element where you want to find the links.

obj = $( "a" ).find( allLinkElements ); console.log(obj);

add a class to all of them, using the target element to only add css to those within

$( "#content" ).find( allLinkElements ).css( "background-color", "red" );

test with the link elements and css change

var allLinkElements = $( "a" ); $( "#content" ).find( allLinkElements ).css( "background-color", "red" );

you can copy and paste that into the console and it should change the background color of all links in #content to red.

now try adding a class

var allLinkElements = $( "a" ); $( "#content" ).find( allLinkElements ).addClass( "btn btn-primary");

Here are some test links that should change to buttons if you run this code.

A Test Link

A Test Link

A Test Link

A Test Link

A Test Link

if we didnt add the #content to the above command it would change all links on the whole page to buttons which could cause issues.

then we can remove the class with removeClass, you can also just use toggleClass.

var allLinkElements = $( "a" ); $( "#content" ).find( allLinkElements ).toggleClass( "btn btn-primary");

Demo

Other Items in js
Page Views

This page has been viewed 42 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹