KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
How do you test an element for existence without the use of the getElementById method? I have set up a live demo for reference. I will also print the code on here as well: <!DOCTYPE html> <html> <head> <script> var getRandomID = function (size) { var str = "", i = 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 be true? console.log('null', (image === null) ? true : false); // false ~ should be true? console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this? }; </script> </head> <body> <div id="demo"></div> </body> </html> Basically the above code demonstrates an element being stored into a variable and th
Tags (comma-separated)
Save Edits
Cancel