使用parentElement.getElementsByClassName在元素上隐藏/设置不显示



我试图隐藏一个按钮,该按钮在被点击后创建一个新元素(然后被删除所取代(,但我似乎无法将显示更改为"none";当我尝试使用parentElement以相同的元素为目标,然后按类名获取元素时。

我想这样做的原因是让其他元素以同样的方式可见,但这超出了我现在遇到的问题的范围。

我在下面输入了我的问题示例。

let template = '<div><button onclick="createNewElement(this)" class="js-create-button">+</button> </div>'

function createNewElement(e){
e.parentElement.parentElement.innerHTML += template; // Creating new button using the template
let a = document.getElementsByClassName("js-create-button")[0];  // Getting the element using document
let b = e.parentElement.getElementsByClassName("js-create-button")[0];  // Getting the element using a parent element (this is the line that's causing issues)
console.log(a);  // Both logs return the correct element, but only the first one works when i change the styling
console.log(b);
a.style.background = "red";
b.style.background = "blue";
}
<body>

<div>
<div>    
<button onclick="createNewElement(this)" class="js-create-button">+
</button>
</div>
</div>
</body>

在这个例子中,我改变了样式,以便更容易地看到哪些不起作用。样式应该变成蓝色,而不是红色,这也适用于第一个元素之后创建的所有元素。

不知何故,返回的元素似乎是一个";复制";原来的,所以改变它没有任何作用。

通过执行e.parentElement.parentElement.innerHTML += templatee.parentElement.parentElement的实际内容的上下文将丢失。

这样做将保留上下文

let template = '<div><button onclick="createNewElement(this)" class="js-create-button 22">+</button> </div>'

function createNewElement(e) {
let newDiv = document.createElement('div');
newDiv.innerHTML = template
e.parentElement.parentElement.append(newDiv.firstElementChild); // Creating new button using the template
let a = document.getElementsByClassName("js-create-button")[0]; // Getting the element using document
let b = e.parentElement.getElementsByClassName("js-create-button")[0]; // Getting the element using a parent element
console.log(a); // Both logs return the correct element now
console.log(b);
a.style.background = "red";
b.style.background = "blue";
}
<div>
<div>
<button onclick="createNewElement(this)" class="js-create-button">+
</button>
</div>
</div>

最新更新