首页 > 解决方案 > 添加元素的多个实例

问题描述

我有一个使用创建的标题元素document.createElement

let h1 = document.createElement("h1");
h1.innerHTML = "Heading"

<div>体内也有空:

<div></div>

当我使用document.body.appendChild(h1)时,它按预期执行:

<h1>Heading</h1>
<div></div>

但我想将h1元素附加到主体<div>主体。问题是appendChild如果元素已经被附加,它会移动它。

阻止我修改innerHTML或克隆的事情是,假设我想更改元素的实例的 innerHTML 所以为此我需要访问元素的 DOM。而且我可能不知道实例的确切位置是什么。

有谁知道其他方法可以做到这一点或解决方法appendChild

标签: javascripthtmldom

解决方案


更新后的对话

//create function that makes loops through each query. We are using query selctor here.
function appendIt (a,b){
for (let i = 0; i < a.length; i++) {
let h1 = document.createElement("h1");
h1.innerHTML = b;
  document.querySelector(a[i]).appendChild(h1);

}

};
//simply run query to get the desired effect on inner html 
function updateIt (a,b){
for (let i = 0; i < a.length; i++) {
  document.querySelector(a[i]).innerHTML = b;
  
}

}; 


//magic in action
appendIt (['body', 'div'],'heading');
updateIt (['body>h1', 'div>h1'],'headingsssss');
<!DOCTYPE html>
<html>
<body>
<div></div>
</body>
</html>

注意在示例中;

//problem statement innerHTML is using js getter and setter function behind the scene. It takes one time value and never gets trigered again when original value assigned is changed.  
let abc = 'heading';
let h1 = document.createElement("h1");
h1.innerHTML = abc;
document.body.appendChild(h1);
//below chnage will have no effect.
abc = 'heading2';
   //To bring to effect innerHTML will have to be triggered again.
<div></div>

let abc = 'heading';
let h1 = document.createElement("h1");
h1.innerHTML = abc;
document.body.appendChild(h1);
h1.innerHTML = 'heading2';
abc = 'heading3';
//innerHTML triggered again.
<div></div>

现在,无论您克隆它还是其他方式,您都必须创建一个设定克隆数量的函数并相应地附加它们,然后创建一个更新函数,它将循环每个元素并一个一个地更改 innerHTML。

附加示例:

//adavnce magic in action

//create a proxy and create a trap on setter
let proxy = new Proxy({}, {
    
    set(target, property, value) {
        if (property == 'data'){
        target['display'](value);
        target['data'] = value;
//for any other propety just set the value as it is
        } else {target[property] = value;}

        
    }
});
//give it a list of elements to work with 
proxy.list = ['body', 'div'];
proxy.display = function (a){
//run a little check if items are added if so simply update
if(proxy.status) {
for (let i = 0; i < proxy.list.length; i++) {
  document.querySelector(proxy.list[i]+'>h1').innerHTML = a; 
} 

}

//or add items
else {

    for (let i = 0; i < proxy.list.length; i++) {
    let h1 = document.createElement("h1");
    h1.innerHTML = a;
      document.querySelector(proxy.list[i]).appendChild(h1);
    
    }
    
    proxy.status = true;
    
    }


}; 

//Let the fireworks rip
proxy.data=48;
// Get a cup of tea and some biscuits
setTimeout(function(){proxy.data=57; }, 3000);
<!DOCTYPE html>
<html>
<body>
<div></div>
</body>
</html>

其他示例正是您想要的,并且将在变量的单个更改(尽管作为对象)上更新所有内容。


推荐阅读