为 dom 操作编写代码时的最佳做法是什么?

What is best practice when writing code for dom manipulation?

所以我正在创建一个网络应用程序,它获取食谱信息并根据食物食谱 API 将其打印到 DOM。我正在获取 JSON 信息并大量操纵 dom。我突然意识到这段代码很难读。这是一个片段:

//create ingredient title

const ingredientTitle = document.createElement("p");

const ingredientTitleTextNode = document.createTextNode("Ingredients");

ingredientTitle.appendChild(ingredientTitleTextNode);

const ingredientTitleParent = document.querySelector(".recipe-ingredients-item");

ingredientTitleParent.appendChild(ingredientTitle);

//create ingredient title end



//create ingredient UL and LIs

const ingredients = selectedItemJson.hits[0].recipe.ingredientLines;


const ingredientUl = document.createElement("ul");

for (let j = 0; j < ingredients.length; j++) {

  const ingredientLi = document.createElement("li");

  const ingredientTextNode = document.createTextNode(ingredients[j]);

  ingredientLi.appendChild(ingredientTextNode);

  ingredientUl.appendChild(ingredientLi);

}

const ingredientParent = document.querySelector(".recipe-ingredients-item");

ingredientParent.appendChild(ingredientUl);

//create ingredient UL and LIs end

还会有更多这样的内容。那么这是不好的做法吗?如果是这样我能做什么。提前致谢。

1) 使用 innerHTML 的快速简单示例:

var html = "";
var list = [
    {
        name: "name",
        components: [
            {name: "ingredient1", quantity: "q1"},
            {name: "ingredient2", quantity: "q2"}
        ]
    },
    {
        name: "name2",
        components: [
            {name: "ingredient3", quantity: "q1"},
            {name: "ingredient4", quantity: "q2"}
        ]
    },

]

for (var x = 0; x < list.length; x++){
    var item = list[x];
    html += "<h1>" + item.name + "</h1>";
    html +="<ul>";
    for (var y = 0; y < item.components.length; y++){
        var component = item.components[y];
        html += "<li>" + component.name + ", quantity: " + component.quantity + "</li>";
    }
    html += "</ul>";
}
var dom = document.createElement("p");
dom.innerHTML = html;
document.getElementsByTagName("body")[0].appendChild(dom);

2) 使用直接 dom

var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
body.appendChild(p);

for (var x = 0; x < list.length; x++){
    var item = list[x];
    var h1 = document.createElement("h1");
    h1.innerText = item.name;
    p.appendChild(h1);
    var ul = document.createElement("ul");
    for (var y = 0; y < item.components.length; y++){
        var li = document.createElement("li");
        var component = item.components[y];
        li.innerText = component.name + ", quantity: " + component.quantity;
        ul.appendChild(li);
    }
    p.appendChild(ul);
}

JSPerf 测试 InnerHTML 与直接 dom

https://jsperf.com/innerhtml-vs-dom-append/1