我有这个jQuery代码,但是我需要将它转换成普通的Javascript,因为我正在工作的项目没有使用jQuery这里是我尝试过的,但是它没有工作。 我不确定我所做的所有这些改变
null
// My current jQuery code
$('#category-2 ul li').each(function() {
$(this).find("ul.top-menu").parent().remove();
});
$('#category-2>a').html("Produkte");
// Vanilla JS
document.querySelectorAll('#category-2 ul li').forEach(function() {
this.find('ul.top-menu').parentNode().removeChild();
});
document.querySelectorAll('category-2>a').innerHTML="Produkte";
null
您的代码中有几个问题。 一个是在函数中使用this关键字,就像在类中使用一样,但是在函数中this关键字并不是指您期望它是什么。 而是使用forEach函数中的参数:item,index,array,thisArg可以使用。
第二个问题是,在Vanilla JS中没有find()方法,因此我建议实现一个三元运算符(一行if语句)来检查类名或id是否包括您正在搜索的内容。
我不确定您正在搜索哪些项目,如果没有html很难分辨,但是看起来应该是这样的:
// Vanilla JS
document.querySelectorAll("#category-2").forEach(item => {
item.className.includes("top-menu") && item.parentNode.removeChild();
});
document.querySelectorAll("#category-2").forEach(item => {
item.innerHTML = "Produkte";
});