问题描述
是否可以确定文档中是否还存在保存到变量中的元素?我尝试了以下操作,并且在删除第二个INPUT标签时,它不会输出console.log()。
<input type="text">
<input type="email">
<input type="tel">
<script>
var ref= [document.getElementsByTagName('INPUT')[0],document.getElementsByTagName('INPUT')[1],document.getElementsByTagName('INPUT')[2]];
document.getElementsByTagName('INPUT')[1].outerHTML = '';
if (!document.contains(ref[1])) {
console.log('deleted')
}
</script>
解决方法
您的代码失败,因为您删除了索引1
处的元素,这将索引2
处的元素下移到该索引。
通常,不要做所有的DOM选择。为变量选择一次,然后重新使用该集合。绝对不是将集合转换为数组的方法。
但是,即使具有缓存列表,它仍然是实时列表,因此仍然会发生相同的重新索引。
因此,将该元素存储到其自己的变量中,然后对其进行测试。
var inputs = document.getElementsByTagName('INPUT');
var barElem = inputs[1];
barElem.remove();
if (!document.contains(barElem)) {
console.log('deleted')
}
<input value="foo"><input value="bar"><input value="baz">
此外,使用.outerHTML = ''
是删除元素的一种非常荒谬的方式,因此我将其更新为使用barElem.remove()
。
这里是我如何编写代码的示例:
guysArray = new [] {
new Guy { myName="Joe",MyCashInBank=50,myRadioButton=JoeRadioButton,myLabel=JoeBetLable,myBet=null },new Guy { myName = "Rob",MyCashInBank = 75,myRadioButton = RobRadioButton,myLabel = RobBetLabel,myBet = null },new Guy { myName = "Al",MyCashInBank = 45,myRadioButton = AlRadioButton,myLabel = AlBetLabel,};
let doc,htm,bod,nav,M,I,mobile,S,Q; // for use on there loads
addEventListener('load',()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false
S = (selector,within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector,within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
// magic under here
const inputs = Q('.main>input');
inputs[1].remove();
if(!bod.contains(inputs[1])){
console.log('removed');
}
}); // end load
/* css/external.css */
*{
box-sizing:border-box; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#333; overflow-y:auto; padding:10px;
}
input{
margin-left:7px;
}
input:first-child{
margin:0;
}
请注意,我删除了输入之间的空格,因为HTML中的一个或多个空格等于包含该空格的Element当前字体大小的一个空格。另外,最佳做法是使用外部CSS和JavaScript,因此要对其进行缓存。