In the future it's useful to include HTML, and have an example in the form of a snippet for us to play around with.
I've just made a snippet where your 'content' divs are wrapping the buttons. Arthur's answer is great and will work perfectly. An alternative (that I'm showing here) is to grab the id name of the button (you can access it by passing the event to the function then using e.target
to access the element), extracting the number after the hyphen, then fetching the content div afterwards.
I stole the random color generator here:
Random color generator
to change the div background so that you can see that clicking on the button affects the right div.
function onButtonClick(e) {
const targetNum = e.target.id.split("-")[1];
document.querySelector('#open-'+targetNum).style.backgroundColor = getRandomColor();
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<div id="open-1" style="padding: 5px; border: 1px solid #ccc">
<button id="no-1" onclick="onButtonClick(event)">button 1</button>
</div>
<div id="open-2" style="padding: 5px; border: 1px solid #ccc">
<button id="no-2" onclick="onButtonClick(event)">button 2</button>
</div>
<div id="open-3" style="padding: 5px; border: 1px solid #ccc">
<button id="no-3" onclick="onButtonClick(event)">button 3</button>
</div>
<div id="open-4" style="padding: 5px; border: 1px solid #ccc">
<button id="no-4" onclick="onButtonClick(event)">button 4</button>
</div>