ANURAG GOLDEN
ANURAG GOLDEN

Reputation: 65

How to toggle class from a child to another in html

<html>
<head><title>Don't Know</title>
</head>
<body>
<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>
</body>
</html>

I want to toggle class "random" from one child (p tag) to another child(p tag). How am I supposed to do that with less Javascript/Jquery code?

Upvotes: 1

Views: 50

Answers (3)

tranminhquang
tranminhquang

Reputation: 115

just add:

 const childEl = document.querySelectorAll(".child");
 childEl.forEach((child) => {
    child.addEventListener("click", () => {
        document.querySelector(".random").classList.remove("random");
        child.classList.add("random");
     });
 });

Upvotes: 0

s.kuznetsov
s.kuznetsov

Reputation: 15213

And this decision is from me.

$('.child').on('click', function() {
  $('.child').removeClass('style_for_p');
  $(this).addClass('style_for_p');
});
.child {
  cursor: pointer;
}

.style_for_p {
  color: green;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>

Upvotes: 1

sbgib
sbgib

Reputation: 5828

Try like this:

.random {
 color: red;
}
<html>
<head><title>Don't Know</title>
</head>
<body>
<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>
<script>
document.querySelectorAll(".child").forEach((child) => {
  child.onclick = () => {
     document.querySelector(".random").classList.remove("random");
     child.classList.add("random");
  };
});
</script>
</body>
</html>

Click on a p element to remove the random class from where it was before and add it to the new element.

Upvotes: 1

Related Questions