Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley matthewstokeley/hasAttr.js
Last active Nov 13, 2019

Embed
What would you like to do?
does an element have an attribute
// has
const hasAttr = ( _el, attr ) => {
if ( ! _el.children[0] ) {
return false;
}
if ( _el.nodeType !== 1) {
return false;
}
if ( ! typeof attr === 'string' ) {
return false;
}
let res = {
att: false,
value: ''
}
const writeObj = function ( values ) {
let cache = new WeakMap();
let val = '';
for ( key, value in values ) {
val = defineObjValue( key, {
value: value
} ).call( res )
}
return cache.add( 'key', val );
}
const defineObjValue = function( key, writeObj ) {
// single use principle makes for more streamlined write api's
if ( ! writeObj.writeable ) {
writeObj.writeable = true;
}
Object.defineProperty( this, key, writeObj )
return this
}.bind(res)
/**************************
* what does this api look like
*
* writeObj({
* att: 'class',
* value: 'classList classListModifier className'
* })
*
* alternative tree structure
* writeObj(['att', 'class', 'value', 'className'])
*
*/
// order of precedence
// micro-optimizations would select attribute types that are used first
if ( _el[ attr ] ) {
if ( Array.isArray( _el[ attr ] ) ) {
// if 0 index is undefined
}
if (typeof _el[ attr ] === 'object' ) {
// if hasOwnProperty count === 0
/*************************************************
* First implementation
*
*/
let ownPropertyCount = 0;
// technically within the same block
for (key, prop in obj) {
obj.hasOwnProperty(prop) ?? ++ownPropertyCount;
}
if ( ownPropertyCount > 0 ) {
return true;
}
/*************************************************
* Alternative implementation
* - this is the more standard approach
*/
for (key, prop in obj) {
if ( obj.hasOwnProperty(prop) ) {
return true;
}
}
}
// @todo optional chaining
if (typeof _el[ attr ] === 'string' ) {
if ( _el[ attr ] === undefined ||
_el[ attr ] === '' ) {
return true;
}
}
return true;
}
if ( _el.data[ attr ] ) {
return writeObj.call(res, 'attr', _el.data[ attr ])
}
for ( let i = 0; i < el.children; i++ ) {
if ( el.children[ i ][ attr ] ) {
return {
child: true;
}
}
}
//for ( let i = 0; i < el. )
}
module.exports = hasAttr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.