Adding and Deleting from objects in javascript -



Adding and Deleting from objects in javascript -

i pretty sure have right, trying add together , delete using 2 separate method in javascript code.

the first one, trying add together classstr html element object el, property of classname. if contains classstr, left alone.

var addclass = function addclass(el, classstr) { if(el.classname !== classstr) { el.classname = classstr; } };

this one, trying delete classstr classname without leaving white spaces. el element object. thing unsure about, if leaving white spaces.

var removeclasfunction = function removeclass(el, classstr) { delete el.classname; };

the main disadvantage of functions don't handle multiple class names on object. in addition, don't want removing property name, setting empty string when there no class names.

here's set of utility functions managing class names works when there more 1 class name on object should plan (which yours not). these don't accumulate whitespace:

function addclass(elem, cls) { if (!hasclass(elem, cls)) { var oldcls = elem.classname; if (oldcls) { oldcls += " "; } elem.classname = oldcls + cls; } } function removeclass(elem, cls) { var str = " " + elem.classname + " "; elem.classname = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, ""); } function hasclass(elem, cls) { var str = " " + elem.classname + " "; var testcls = " " + cls + " "; return(str.indexof(testcls) !== -1) ; } function toggleclass(elem, cls) { if (hasclass(elem, cls)) { removeclass(elem, cls); } else { addclass(elem, cls); } }

javascript

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -