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>
CodePudding user response:
Since oyu cant add an 'onlcik' on the html, I was thinking you could call the javascript by injecting it with JavaScript with the setAttribute()
method.
Hre is the code
function set_event(){
const Div1 = document.getElementById('div1');
const Div2 = document.getElementById('div2');
const Div3 = document.getElementById('div3');
const Div4 = document.getElementById('div4');
Div1.setAttribute("onclick", "changeElement(1)");
Div2.setAttribute("onclick", 'changeElement(2)');
Div3.setAttribute("onclick", 'changeElement(3)');
Div4.setAttribute("onclick", 'changeElement(4)');
}
window.onload = set_event();
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 id='div1'>Div 1</span>
<span id='div2'>Div 2</span>
<span id='div3'>Div 3</span>
<span id='div4'>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>
<script>
</script>