i want to make the color of the number green if its more than zero to make it green and want to be red when its below zero but i cant do it i dont get why can anyone explain
const button1 = document.querySelector('.prevBtn');
const button2 = document.querySelector('.nextBtn');
const main = document.querySelector('.main-container')
const count = document.getElementById('counter')
let counter = 0
main.addEventListener('click', e => {
if(e.target.classList.contains('nextBtn')){
counter
html=`
<h1 >counter</h1>
<h1 id="counter"class =count">${counter}</h1>
<div >
<button >lower count</button>
<button >add count</button>
`
main.innerHTML = html
}else if(e.target.classList.contains('prevBtn')){
counter--
html=`
<h1 >counter</h1>
<h1 id="counter">${counter}</h1>
<div >
<button >lower count</button>
<button >add count</button>
`
main.innerHTML = html
}
})
if(counter > 0){
count.style.color = 'green'
} else if(counter < 0) {
count.style.color = 'red'
}
CodePudding user response:
The order in your code is not correct. You must get an element after it is added to DOM.
Try the snippet.
const main = document.querySelector('.main-container')
let counter = 0
main.addEventListener('click', e => {
if(e.target.classList.contains('nextBtn')){
counter
html=`
<h1 >counter</h1>
<h1 id="counter"class =count">${counter}</h1>
<div >
<button >lower count</button>
<button >add count</button>
`;
main.innerHTML = html
}else if(e.target.classList.contains('prevBtn')) {
counter--
html=`
<h1 >counter</h1>
<h1 id="counter">${counter}</h1>
<div >
<button >lower count</button>
<button >add count</button>
`;
main.innerHTML = html
}
const button1 = document.querySelector('.prevBtn');
const button2 = document.querySelector('.nextBtn');
const count = document.getElementById('counter')
if(counter > 0){
count.style.color = 'green'
} else if(counter < 0) {
count.style.color = 'red'
}
});
.main-container {
width: 100%;
height: 500px;
}
<div >Click On Me</div>