classname - How do I add a class name to Javascript string? -
i'm js newbie trying alter following code. looks it's adding style attributes. add class name "reveal" string or below. syntax like? many help, guys!
inline = ( elem.domel.getattribute( 'style' ) ) ? elem.domel.getattribute( 'style' ) + '; visibility: visible; ' : 'visibility: visible; '
(i guess) html may this:
<div class="some other">
in such case, if like
elem.domel.classname = 'reveal';
then you'll get
<div class="reveal">
all styles brought class some , other gone! don't want that, right? don't want repeated classname, like
<div class="reveal reveal">
so, here solutions:
the best way use html5 api classlist
:
elem.domel.classlist.contains('reveal') // check whether element has classname elem.domel.classlist.add('reveal') // add classname elem.domel.classlist.remove('reveal') // remove classname elem.domel.classlist.toggle('reveal') // toggle classname
if still want run code in out-dated browsers, try these:
// check whether element has classname function hasclass(ele, cls) { var clschecker = new regexp("\\b" + cls + "\\b"); return clschecker.test(ele.classname); } // add classname function addclass(ele, cls) { var clschecker = new regexp("\\b" + cls + "\\b"); if(clschecker.test(ele.classname)) { // ele has classname, don't need return; } ele.classname += (' '+ cls); } // remove classname function removeclass(ele, cls) { var clschecker = new regexp("\\b" + cls + "\\b"); if(clschecker.test(ele.classname)) { // ele have classname, remove them (in case repeated) ele.classname.split(clschecker).join(''); } } // toggle classname function toggleclass(ele, cls) { var clschecker = new regexp("\\b" + cls + "\\b"); if(clschecker.test(ele.classname)) { // ele have classname, remove them (in case repeated) ele.classname.split(clschecker).join(''); } else { // ele doesn't have classname, add ele.classname += (' '+ cls); } } // usages hasclass(elem.domel, 'reveal') // check whether element has classname addclass(elem.domel, 'reveal') // add classname removeclass(elem.domel, 'reveal') // remove classname toggleclass(elem.domel, 'reveal') // toggle classname
Comments
Post a Comment