Change Class Names Of Multiple Divs With Same Class To Unique Names With Vanilla JS

Hi,

I have a situation where PHP is creating a document that has code blocks that contain the same class names each time the PHP function runs. Sometimes the function runs multiple times on a single post (WordPress PHP function/WordPress post). The PHP function isn’t going to change, so anything I need to do needs to be handled on the client side with vanilla Javascript in my scenario.

Scenario:

So, let’s say I have 3 divs with the same class name. I want to use JS to first find the divs (I know I can use document.querySelectorAll() for that) and then assign unique pre-defined class names for each div that’s found in the resulting nodelist.

Example: From PHP, I ended up with the following 3 pre-JS divs:

<div class="myDiv">
<div class="myDiv">
<div class="myDiv">

Using the resulting nodelist (or some other method), I need to identify each of these divs and rename them with JS to my pre-defined names. I want to end up like this:

<div class="Unique-1">
<div class="Unique-2">
<div class="Unique-3">

After renaming the divs, I then want to be able to target the unique names with a CLICK action. I know how to do that. It’s actually the renaming part I need help with in terms of JS properties/methods, acting on a nodelist or some other way. I won’t always be sure in advance how many of these same-named divs I’m going to have, so I’m thinking I need a pre-defined ARRAY of div names that will be assigned in a sequential order via a loop, where the loop breaks off after the number of divs found/renamed has been satisfied.

To be clear, I need to know in advance that the first div of the same class name in the document is going to be renamed (as an example) “Unique-1”, and successively thereafter.

Can this be done?

Thanks.

Hi @SlikkRick, you can iterate over the elements using forEach() and then add a class to the classList like so:

document.querySelectorAll('.myDiv').forEach((element, index) => {
  element.classList.add(`unique-${index}`)
})

What do you mean with predefined though? Are those classes not supposed to be generated dynamically?

But then you might as well add the event listener directly:

document.querySelectorAll('.myDiv').forEach((element, index) => {
  element.addEventListener('click', event => {
    console.log(`myDiv ${index} received:`, event)
  })
})

(Of course you can do both if it is actually necessary.)

Sorry for not being clear - I absolutely need to know what each div - in the order they appear in the document - is going to be renamed. So Div 1 would be renamed Unique-1, etc. Looks like the index number will do that. Thanks!

No worries! :-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.