I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them.
In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding paragraph to be displayed.
While I managed to achieve this functionality with buttons that have onclick attributes, I'm facing difficulties implementing it for columns.
I would appreciate assistance in reviewing the code and figuring out how to use JavaScript to change paragraphs by calling an ID without explicitly using onclick in the HTML. The onclick behavior could be defined in either 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>