คุณจะทดสอบองค์ประกอบของการดำรงอยู่ได้อย่างไรโดยไม่ต้องใช้ getElementByIdวิธีการได้อย่างไร?
ฉันได้ตั้งค่าการสาธิตสดสำหรับการอ้างอิง ฉันจะพิมพ์รหัสที่นี่เช่นกัน:
<!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>โดยทั่วไปรหัสข้างต้นแสดงให้เห็นถึงองค์ประกอบที่ถูกเก็บไว้ในตัวแปรแล้วลบออกจาก DOM แม้ว่าองค์ประกอบจะถูกลบออกจาก DOM ตัวแปรยังคงรักษาองค์ประกอบเหมือนเดิมเมื่อประกาศครั้งแรก กล่าวอีกนัยหนึ่งมันไม่ใช่การอ้างอิงสดถึงองค์ประกอบ แต่เป็นการจำลอง ดังนั้นการตรวจสอบค่าของตัวแปร (องค์ประกอบ) สำหรับการมีอยู่จะให้ผลลัพธ์ที่ไม่คาดคิด
 isNullฟังก์ชั่นเป็นความพยายามของฉันที่จะตรวจสอบสำหรับการดำรงอยู่ขององค์ประกอบจากตัวแปรและการทำงาน แต่ผมอยากจะทราบว่ามีวิธีที่ง่ายขึ้นเพื่อให้บรรลุผลเดียวกัน
PS: ฉันยังสนใจว่าทำไมตัวแปร JavaScript ที่ทำตัวเป็นแบบนี้ถ้าใครรู้บทความดีๆเกี่ยวกับเรื่องนี้