我需要向所有具有 class 的元素添加一个带有 class 的 div '.cart-list-value .delete-product'
,其中包含背景图像.cart-list-item
。我能够使用 class 获取所有元素.carl-list-item
,但是当我添加新元素时,它只是添加到最后一个元素。
export class ShopViewCartViewComponent implements OnInit {
constructor(
private renderer: Renderer2,
private elem: ElementRef,
protected cartService: CartService <BaseCartItem>
) {}
ngOnInit(): void {}
ngAfterViewInit() {
const child = document.createElement("div");
child.addEventListener('click', this.onClick.bind(this));
child.classList.add('cart-list-value', 'delete-product');
const elements = this.elem.nativeElement.querySelectorAll('.cart-list-item');
elements.forEach(element => {
this.renderer.insertBefore(element, child, element.childNodes[0]);
});
console.log(elements);
}
onClick(event) {
console.log(event);
}
}```
[here you can see what is the result][1]
[1]: https://i.stack.imgur.com/obrdM.png