-1

I want to change style of element above element that I clicked using JavaScript. I know how to change stye of element that I clicked, but I want to also change style element of the on above. I started with something like that, and now I am stuck.

let elems = document.getElementsByTagName("p")
for (var i = 0; i < elems.length; i++) {
  elems[i].onclick = function() {
    this.style.border = "thick solid green";
    elems[i + 1].style.border = "thick solid yellow"
  };
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div id=buttons>
    <p type="button"> p1 </p>
    <p type="button"> p2 </p>
    <p type="button"> p3 </p>
    <p type="button"> p4 </p>
    <p type="button"> p5 </p>
    <p type="button"> p6 </p>
    <p type="button"> p7 </p>
  </div>
</body>

</html>

I know I should add if to possibility of clicking the top element, but for now it is not my problem.

Should I use eventListener? What can I do?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Anz
  • 49
  • 6

1 Answers1

0

Use this.previousElementSibling to get the element before the current one.

See Javascript infamous Loop issue? for why your code doesn't work, and other ways to fix it.

let elems = document.getElementsByTagName("p")
for (var i = 0; i < elems.length; i++) {
  elems[i].onclick = function() {
    this.style.border = "thick solid green";
    let prev = this.previousElementSibling;
    if (prev) {
      prev.style.border = "thick solid yellow";
    }
  };
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div id=buttons>
    <p type="button"> p1 </p>
    <p type="button"> p2 </p>
    <p type="button"> p3 </p>
    <p type="button"> p4 </p>
    <p type="button"> p5 </p>
    <p type="button"> p6 </p>
    <p type="button"> p7 </p>
  </div>
</body>

</html>
Barmar
  • 741,623
  • 53
  • 500
  • 612