Home > other >  Trying add class to element HTML doesn't work
Trying add class to element HTML doesn't work

Time:10-14

I'm trying to add classes to different div, but I don't know why it doesn't work when I had created the class in the . sass file, and after that add using className, setAttribute or classList. But, when I do it in the same .ts file, works perfectly.

work

const tamano = 75;
const customMarker: HTMLElement = document.createElement('div');
customMarker.style.backgroundImage = `url(${this.greenShip})`;
customMarker.style.width = `${ tamano }px`
customMarker.style.height = `${ tamano }px`
customMarker.style.backgroundSize = '100%';
customMarker.style.cursor = 'pointer'

Doesn't work

const customMarker: HTMLElement = document.createElement('div');
customMarker.setAttribute('id', 'id_ship-on-time');
customMarker.setAttribute('class', 'ship-on-time');
console.log(customMarker.outerHTML);
customMarker.className = "ship-on-time";

class

.ship-on-time
  background-image: url('../../../../../assets/icons/[email protected]')
  background-size: contain
  width: 70px
  height: 70px
  cursor: pointer
  background-repeat: no-repeat

The result in the console is that

console result

CodePudding user response:

Ensure that your CSS class has the proper syntax:

.ship-on-time {
  background-image: url('../../../../../assets/icons/[email protected]');
  background-size: contain;
  width: 70px;
  height: 70px;
  cursor: pointer;
  background-repeat: no-repeat;
}

CodePudding user response:

First, write your class in your .sass file

.ship-on-time {
  background-image: url('../../../../../assets/icons/[email protected]');
  background-size: contain;
  width: 70px;
  height: 70px;
  cursor: pointer;
  background-repeat: no-repeat;
}

then, if you want to add this class using the DOM, you need to use classList

customMarker.classList.add("ship-on-time");
  • Related