'How do i get my DIVS to change content just like the buttons, without adding an onclick function on the html
I am working with a WordPress theme which has no input for onclick on the divs. But i can assign classes and IDs only.
I have four spans in a row, and onclick of each column, I want the corresponding paragraph to show.
I was able to do for buttons that have onclick properties, but unable to do for the columns.
Please help review the code and see how I can a JS to call the paragraphs to change by calling an ID, without having to put on click on the HTML. The on-click can be in the JavaScript or CSS.
function changeElement(num) {
document.getElementById(`paragraph_${num}`).style.display = 'block';
const arr = [1, 2, 3, 4].filter((elem) => elem !== num);
arr.forEach((elem) => {
document.getElementById(`paragraph_${elem}`).style.display = 'none';
})
}
body {
width: 100%;
}
.none {
display: none;
}
div {
display: flex;
flex-direction: row;
gap: 20px;
justify-items: center;
}
span {
height: 50px;
width: 50px;
background-color: green;
}
// the divs that correspond to each button below
<div>
<span>Div 1</span>
<span>Div 2</span>
<span>Div 3</span>
<span>Div 4</span>
</div>
<p id="paragraph_1">paragraph 1</p>
<p id="paragraph_2" class="none">paragraph 2</p>
<p id="paragraph_3" class="none">paragraph 3</p>
<p id="paragraph_4" class="none">paragraph 4</p>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
