0

I'm coming back with another problem.

I have such code:

HTML

<button>first</button>
<button>second</button>

<div class="first"></div>
<div class="second"></div>

CSS

div{
  margin-top: 10px;
  width: 100px;
  height: 100px;
  border:1px solid black;
  background-color: #ddd;
}

JS

const btns = document.querySelectorAll("button");
const first = document.querySelector(".first");
const second = document.querySelector(".second");

btns.forEach(btn => btn.addEventListener("click", function(){
  this.classList.toggle("pressed");
  let selection = this.textContent;

  // selection.style.transform = "translate(100px)";
}))

https://codepen.io/ptr11dev/pen/oREymM

I'd like to create one function that'll be responsible for moving respective div to the right side by 100px - I stuck with such problem. Under "selection" I have respective name of div (stored under the same name), but simple code like

selection.style.transform = "translate(100px);"

doesn't work. I know that workaround like creating two functions and using

first.style.transform = "translate(100px);"

and

second.style.transform = "translate(100px);"

would work, but in my main code it's a bit more complicated.

I'll really appreciate any input from your side. Thanks

P.S. I'd like to use Vanilla JS.

Vontar
  • 64
  • 4

2 Answers2

1

Your problem is textContext is just that TEXT not an object. This sets selection as the first element that matches the class name pulled as this.textContent;

let selection = document.getElementsByClassName(this.textContent)[0];
selection.style.transform = "translate(100px)";
imvain2
  • 15,480
  • 1
  • 16
  • 21
  • Hmm.. That would work but it means I have two references to the same object. – Vontar May 23 '19 at 16:11
  • @PiotrKaczmarek, if you aren't using `first` and `second` then you don't need to declare them. My answer just like the other answer does the same thing in two different methods. You can rig something up using `eval` or some weird array, but you are then overcomplicating things just so you can reuse the variables that you already declared, – imvain2 May 23 '19 at 16:14
  • Yea, I've rewrote my project so that worked. Thank you very much! – Vontar May 23 '19 at 16:21
1

You can find them by the class name, assuming that the button text and their class are the same.

const btns = document.querySelectorAll("button");
const first = document.querySelector(".first");
const second = document.querySelector(".second");

btns.forEach(btn => btn.addEventListener("click", function(){
  this.classList.toggle("pressed");
  let selection = this.textContent;
  
  document.querySelector(`.${selection}`).style.transform = "translate(100px)";
}))
div{
  margin-top: 10px;
  width: 100px;
  height: 100px;
  border:1px solid black;
  background-color: #ddd;
}
<button>first</button>
<button>second</button>

<div class="first"></div>
<div class="second"></div>
Paul Cosma
  • 303
  • 2
  • 11