javascript - How do we convert jQuery remove class from parent in VanillaJS -
i'm trying convert jquery method vanillajs below.
jquery:
elements.parent(".item").removeclass("item"); vanilla :
var parent = elements.parentnode; parent.queryselector(".item").classlist.remove('item'); but vanilla script not working same jquery. please suggest better solution.
given elements plural, i'm assuming it's collection, use .foreach(). (this needs patched in legacy browsers unless elements actual array)
elements.foreach(function(el) { el.parentnode.classlist.remove("item"); }); note not need filter down .item elements. if doesn't have class, it'll no-op.
also note .queryselector searches descendants. if did need filter on class other reasons, you'd use .matches.
elements.foreach(function(el) { var par = el.parentnode; if (par.matches(".item")) { // work `.item` element par.classlist.remove("item"); } }); if there multiple ancestors .item class, traverse ancestors in nested loop.
elements.foreach(function(el) { var par = el.parentnode; { if (par.matches(".item")) { // work `.item` element par.classlist.remove("item"); } } while((par = par.parentnode)); }); you make helper function if you're doing frequently.
function ancestors(el, filter) { var res = []; var par = el.parentnode; { if (!filter || par.matches(filter)) { res.push(par); } } while((par = par.parentnode)); return res; } so it's this.
elements.foreach(function(el) { ancestors(el, ".item") .foreach(function(par) { par.classlist.remove(".item"); }); });
Comments
Post a Comment