Javascript: addClassName if input is checked and removeClassName if it was un-checked
I'm trying to select all the li
ta开发者_JS百科gs of the document and check if it hasClassName('yes')
so if it has, it will remove it. But I'm having a TypeError: Object [object HTMLLIElement], has no method 'hasClassName'
error.
This is the DOM method:
document.observe("dom:loaded", function() {
$(document.body).select('input').each(function(element) {
element.observe('click', function() {
init();
});
init();
});
});
The previous code will take the init function and check the if there are checked inputs and add them the 'yes' class name, but if I un-check those inputs, the class remains. This is the function that I'm trying to do dynamic (add and remove class 'yes');
function init() {
$(document.body).select('input').each(function(element) {
if (element.checked) {
element.up('li').addClassName('yes');
}
if ($(document.body).select('li').hasClassName('yes')) {
element.removeClassName('yes');
}
})
}
Can you help me solving the last part of this function, so the removeclassname method will work? Thank you.
$(document.body).select('li')
returns a collection, not an element, right? I would assume you want:
if (element.hasClassName('yes')) {
element.removeClassName('yes');
}
However, it seems that your logic is flawed -- you are first adding the class if the input is checked, then you are immediately removing it. Are you missing an else
? Maybe something more like:
function init() {
$(document.body).select('input').each(function(element) {
if (element.checked) {
element.up('li').addClassName('yes');
}
else {
element.up('li').removeClassName('yes');
}
})
}
Wait a sec - that "select" is going to return an array of elements. The "hasClassName" function is a function on Element directly, not on Array or Enumerable. You're missing an "each()" layer.
$$('li').each(function(li) {
if (li.hasClassName('yes')) li.removeClassName('yes');
});
精彩评论