0
A few days ago I asked a question about how to add class to an elemetho by clicking the button, the answers were satisfactory (I did it using Jquery as suggested), but I decided to create a function using pure javascript only (for study purposes), only there was a bug in the middle of the way and I could not solve, is that someone can find the bug in this code?
sessionStorage.removeItem('Contar');
function AddClass(id){
//pega o valor do botao
var tipo = document.getElementById(id).value;
//pegar o item da lista
var iten = document.getElementsByTagName('li');
//cria uma sessão para gravar os valores dos cliques
if(typeof(Storage)!=="undefined"){
if(sessionStorage.Contar){
if(tipo == 'proximo'){
sessionStorage.Contar=Number(sessionStorage.Contar)+1;
if(sessionStorage.Contar == iten.length){
sessionStorage.Contar=5;
}
}else
if(tipo == 'anterior'){
sessionStorage.Contar=Number(sessionStorage.Contar)-1;
if(sessionStorage.Contar == 0){
sessionStorage.Contar=0;
}
}
}else{
sessionStorage.Contar=0;
}
}
//resgata o valor da sessão
var valor = sessionStorage.Contar
if(tipo == 'proximo'){
if(valor > 0){
//remove a classe do item anterior
iten.item(valor-1).removeAttribute('class');
}
}else
if(tipo == 'anterior'){
if(valor < 5){
//remove a classe do item anterior
iten.item(valor+1).removeAttribute('class');
}
}
//adiciona classe ao próximo item
iten.item(valor).setAttribute('class', 'selected');
}
My html is this:
<button onClick="AddClass('anterior');" id="anterior" value='anterior'>anterior</button>
<button onClick="AddClass('proximo');" id="proximo" value='proximo'>proximo</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
I didn’t post on Jsfidle because on my machine the site is getting all buggy as you can see here:
Give any error on the console?
– Jefferson Alison
Yes, when I click on the "previous" button it gives this error: Uncaught Typeerror: Cannot call method 'removeAttribute' of null
– Odair
So it’s because you’re trying to call this method on an object that hasn’t been initialized. Maybe you have to use brackets instead of parentheses? I think item is an array and not a method, right?
– Oralista de Sistemas
Um dude, I don’t have a very deep knowledge of Javascript, I just started studying a little while ago
– Odair
No, items are accessed in parentheses. Only
if(sessionStorage.Contar == 0)
should besessionStorage.Contar == -1
, nay?– Felipe Avelar