javascript - How to check if element exists in the visible DOM? -
how test element existence without use of getelementbyid method? have setup live demo reference. print code on here well:
<!doctype html> <html> <head> <script> var getrandomid = function (size) { var str = "", = 0, chars = "0123456789abcdefghijklmnopqurstuvwxyzabcdefghijklmnopqurstuvwxyz"; while (i < size) { str += chars.substr(math.floor(math.random() * 62), 1); i++; } return str; }, isnull = function (element) { var randomid = getrandomid(12), savedid = (element.id)? element.id : null; element.id = randomid; var foundelm = document.getelementbyid(randomid); element.removeattribute('id'); if (savedid !== null) { element.id = savedid; } return (foundelm) ? false : true; }; window.onload = function () { var image = document.getelementbyid("demo"); console.log('undefined', (typeof image === 'undefined') ? true : false); // false console.log('null', (image === null) ? true : false); // false console.log('find-by-id', isnull(image)); // false image.parentnode.removechild(image); console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should true? console.log('null', (image === null) ? true : false); // false ~ should true? console.log('find-by-id', isnull(image)); // true ~ correct there must better way this? }; </script> </head> <body> <div id="demo"></div> </body> </html> basically above code demonstrates element being stored variable , removed dom. though element has been removed dom, variable retains element when first declared. in other words, not live reference element itself, rather replica. result, checking variable's value (the element) existence provide unexpected result.
the isnull function attempt check elements existence variable, , works, know if there easier way accomplish same result.
ps: i'm interested in why javascript variables behave if knows of articles related subject.
it seems people landing here, , want know if element exists (a little bit different original question).
that's simple using of browser's selecting method, , checking truthy value (generally).
for example, if element had id of "find-me", use...
var elementexists = document.getelementbyid("find-me"); this spec'd either return reference element or null. if must have boolean value, toss !! before method call.
in addition, can use of many other methods exist finding elements, such (all living off document):
queryselector()/queryselectorall()getelementsbyclassname()getelementsbyname()
some of these methods return nodelist, sure check length property, because nodelist object, , therefore truthy.
for determining if element exists part of visible dom (like question asked), csuwldcat provides better solution rolling own (as answer used contain). is, use contains() method on dom elements.
you use so...
document.body.contains(somereferencetoadomelement);
Comments
Post a Comment