Reputation: 65
<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
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
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
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