Home > Software design >  Inline style with data attribute using JavaScript no jQuery, changing color
Inline style with data attribute using JavaScript no jQuery, changing color

Time:11-21

I have this piece element, which represents a coin in my connect four game, however, I want to change the background color of the coin using inline styling in JS. Is it possible to convert the CSS format to inline js styling? I have tried using getAttribute but don't think I am using right. Any suggestions would be helpful.

style.css:

.piece{
  border-radius: 50%;
  background-color: red;
  flex-grow: 1;
  margin: 5%;
}

.piece[data-placed = "false"]{
  transform: translateY(-10vmin);
}
.piece[data-player = "1"]{                 //This is the element I want to inline style in my js file
  background-color: rgb(25, 0, 255);
}
.piece[data-player = "2"]{                  //This is the element I want to inline style in my js file
  background-color: rgb(255, 0, 0);
}

JS:

//Convert to inline styling

I have tried using the getattribute but doesn't change anything in my webpage.

CodePudding user response:

Assuming you have a HTML markup like:

<div  data-player="1"></div>

Changing its data- attribute's value should do it. So assuming you targeted an element with a data-player="1":

element.dataset.player = "2"

Look the documentation for dataset.

Or:

element.setAttribute("data-player", "2")

CodePudding user response:

just get the element by attribute selector and set its style attribute with background-color

  document
      .querySelector('.piece[data-player="1"]')
      .setAttribute('style', 'background-color: yellow');
  • Related