Path: csiph.com!weretis.net!feeder8.news.weretis.net!news.mb-net.net!open-news-network.org!.POSTED.33.237.197.178.dynamic.wless.lssmb00p-cgnat.res.cust.swisscom.ch!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: check is referenced element still exists Date: Thu, 22 Oct 2020 03:59:04 +0200 Organization: PointedEars Software (PES) Lines: 74 Message-ID: <9780698.nUPlyArG6x@PointedEars.de> References: Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit Injection-Info: gwaiyur.mb-net.net; posting-host="33.237.197.178.dynamic.wless.lssmb00p-cgnat.res.cust.swisscom.ch:178.197.237.33"; logging-data="1332"; mail-complaints-to="abuse@open-news-network.org" User-Agent: KNode/4.14.10 Cancel-Lock: sha1:uSGVfP76OXlw5pLsVjCmiY91YIo= X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. If I have this > > let bar; > > if (document.querySelector('#foo')) { > bar = document.querySelector('#foo'); > } let bar = document.getElementById('foo'); is equivalent to the above, more efficient, and backwards-compatible on the right-hand side. For maximum possible backwards-compatibility, consider var bar = document.getElementById('foo'); and potential wrapper methods. > and at some stage this happens > > bar.remove(); Note that ChildNode::remove(), whose implementation is used there, is specified in the WHATWG DOM only and is not supported by Internet Explorer and older HTML user agents. Use bar.parentNode.removeChild(bar); in backwards-compatible code instead. A wrapper method of the form dom.removeChild = function (childNode) { if (dom.isHostMethod(childNode, 'remove')) { childNode.remove(); } else { childNode.parentNode.removeChild(childNode); } }; may be called instead, and calls to it can be easily replaced (by methods such as full-text search-and-replace) by .remove() calls once backwards compatibility is no longer considered important. > Without directly knowing the element's original ID is the only way to > know whether the referenced element still exists is by doing something > like > > if (document.querySelector(bar.id)) { > //... > } > > ? No. The “parentNode” attribute of Nodes that are not part of a document tree (has not been inserted yet or has been removed already) is specified to be “null” (a OMG/Web IDL special value); therefore, the “parentNode” property of an element object that is not part of a document tree is the “null” value (of the Null type) in ECMAScript implementations. and, more cryptically, -- PointedEars FAQ: | | Twitter: @PointedEars2 | Please do not cc me./Bitte keine Kopien per E-Mail.