I'm trying to change the content in a HTML using DOM JS. Rather than getting the elements by the P tag, I want to use the DIV ID.Is this possible?
In my HTML, I have two separate DIV classes, both named the same. I want one to display depending on what button the user clicks.
HTML:
<button type="button" onclick="changeContent(1)" >Example 1</button>
<button type="button" onclick="changeContent(2)" >Example 2</button>
<p id="demoX"></p>
<div class="ex1">
<h1> Example 1 </h1>
<p> nothing </p>
</div>
<div id="ex1">
<h1> Example 2 </h1>
<p> more of nothing </p>
</div>
JS:
function changeContent(inNum) {
var x = document.getElementById("ex1");
if (inNum == 1){
document.getElementById("demoX").innerHTML = x[0].innerHTML;
}
else if (inNum == 2){
document.getElementById("demoX").innerHTML = x[1].innerHTML;
}
}
How do I approach this?
First of all, you shouldn't give the same ID to more than one div so just give them both the class - 'ex1' - and then you select them by a javascript selector called getElementsByClassName('class-name') [replace class-name with the actual class name, in this case ex1] this function gets all the elements with this class name and stores them in an array. Then you do the logic for which button is pressed. And when a button is pressed you should set the display of the wanted div to 'block' [you should default it to hidden in CSS].
function showDiv(id) {
var divs = document.getElementsByClassName('ex1');
if (id === 'btn1') { divs[0].style.display = 'block' }
if (id === 'btn2') { divs[1].style.display = 'block' }
}
.ex1 {
width: 300px;
height: 300px;
background-color: green;
display: none;
margin: 50px;
}
<button id='btn1' onClick='showDiv(this.id)'>button 1</button>
<button id='btn2' onClick='showDiv(this.id)'>button 2</button>
<div class='ex1'>I'm div 1</div>
<div class='ex1'>I'm div 2</div>
you can also change the .style thing to change the inner html as you have done in your original code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With