Skip to main content
100%

Define in global scope vars for each used CSS classname

✓ Published0🌍 Public
DDougManuel
Last edited Jul 11, 2015
Created on Jul 26, 2015

This example shows a JavaScript utility that automatically creates global jQuery variables named after CSS classnames found in the DOM. The function `defineVarsFromClassName()` scans all elements with a `class` attribute, splits each class name, and assigns a jQuery object reference to a variable like `$className` (with hyphens converted to underscores) if it doesn’t already exist. It relies on jQuery selectors and the global `window` object to store these variables, making class-based DOM access more convenient. The code demonstrates a pattern for reducing repetitive variable declarations in jQuery-heavy projects, using the document’s existing class attributes as the source of variable names.

AI-generated description

Give me a global var named "$"+class name

I do a lot of pens on CodePen and I tend to use the same pattern building a prototype as a pen.

For instance I use classnames as handles when inputting and outputting data to the test/prototype. For instance I would have an element with the classname source and one with output. So I always create var named $source and one called $output.

Why not write a function to automatically add global vars named "$" + classname?

This gist is that function! It will search for elements with classes on them. Run through them and create global vars named "$"+classname, which it then will assign the value of "$(classname)". So after this function have been executed (defineVarsFromClassNames()) in your global (window) scope you can expect to find vars with jQuery reference to the element.

Similar vizzes