I am in the process of creating a universal set of functions to verify the existence of children with specific attributes within a particular element. Unfortunately, I do not have access to jQuery for this task.
Here is an example function call:
has_child_with_id(element, 'obj123');
I am striving to ensure compatibility across various browsers and plan to have distinct functions for finding elements by name, id, class, and more.
Although I am new to the JavaScript module pattern, I am considering if the following approach would be suitable:
var myfunctions = (function() {
var public_interface = {
// NAMED FUNCTION
has_child_with_id: function(el, n) {
return public_interface.has_child_with_('Id', el, n);
},
// GENERIC FUNCTION
has_child_with_: function(type, el, n) {
// Option 1 (querySelectorAll)
return typeof el['querySelectorAll'] === 'function' && el['querySelectorAll']('['+type+'="'+n+'"]').length > 0
// Option 2 (get a bunch of elements, doesn't work on forms)
|| typeof el['getElementsBy'+type] === 'function' && el['getElementsBy'+type](n).length > 0
// Option 3 (get a single element)
|| typeof el['getElementBy'+type] === 'function' && typeof el['getElementBy'+type](n) !== 'undefined'
// Option 4 (Manually loop through elements)
|| (function(children, n) {
for (var i=0;i<children.length;i++) {
if (children[i].hasOwnProperty(type) && children[i][type] == n)
return true;
}
})(el.getElementsByTagName('*', n));
}
};
return public_interface;
})();
alert(myfunctions.has_child_with_id(document, 'myid'));