Solution 1 :

this way

document.querySelectorAll('.selectable.nature').forEach (el => {
  el.addEventListener('mouseover', function(){
    el.classList.add("hover");
    el.classList.remove("nature");
  })
  el.addEventListener('mouseout', function(){
    el.classList.remove("hover");
    el.classList.add("nature");
  })
})
.selectable {
  border: 1px solid darkblue;
  padding: .6em;
  margin: 1em;
  }
.nature {
  background-color: yellow;
  }
.hover {
  background-color: lightblue;
  }
<div class="selectable nature">
  <span>Hello 1</span>
</div>

<div class="selectable nature">
  <span>Hello 2</span>
</div>

Solution 2 :

I use these Vanilla ES6 javascript methods when I can’t use a libray that already includes them.

I can convert them to es2015 if you need.

export const addClass = (element, className) => {
  const cn = element.className
  //test for existence
  if (cn.indexOf(className) !== -1) {
    return
  }
  //add a space if the element already has class
  if (cn !== '') {
    className = ' ' + className
  }
  element.className = cn + className
}


export const hasClass = (element, className) => {
  return new RegExp('(\s|^)' + className + '(\s|$)').test(element.className)
}

export const removeClass = (element, className) => {
  const rxp = new RegExp('\s?\b' + className + '\b', 'g')
  element.className = element.className.replace(rxp, '')
}

Problem :

How to add a class on hover to div where both the div have the same class name.

Here is my HTML.

<div class="selectable nature">
<span>Hello</span>
</div>

<div class="selectable nature">
<span>Hello</span>
</div>

I tried this using javascript but this didn’t work

document.querySelector('.selectable.nature').addEventListener('mouseover', function(){
    var el = document.querySelector('.selectable.nature')
    el.classList.add("hover");
    el.classList.remove("nature");
});

document.querySelector('.selectable.hover').addEventListener('mouseout', function(){
    var el = document.querySelector('.selectable.hover')
    el.classList.remove("hover");
    el.classList.add("nature");
})

Comments

Comment posted by evolutionxbox

querySelector('.selectable.nature')

Comment posted by What do querySelectorAll and getElementsBy* methods return?

Does this answer your question?

Comment posted by PURU

The js load but when I hover it does not have any effect

Comment posted by Mister Jojo

@PURU this code is correct, if you have any problem it may depend on how your css is done, but you haven’t given us a chance to look at this

Comment posted by PURU

But how should I use this, should I use first

By