在值周围包裹一个 HTML 元素

时间:2021-04-01 15:02:39

标签: javascript html jquery

我试图将导航中的元素与 SPAN 关联起来。我怎么做?我已经得到了元素,但现在我需要用 SPAN 包装它。

   let nodes = document.querySelector('nav.bs__pagination').childNodes; 
   const newDiv = document.createElement("div");
      nodes.forEach(function(item) {
       if(item.nodeType == 3) {
         item.insertBefore(newDiv, item);
       }
   });

我试过insertBefore但没有成功,我需要在case之前和之后添加:和

1 个答案:

答案 0 :(得分:1)

您可以创建一个 span 元素,然后将该元素附加到 span 内

const span = document.createElement("span") // Creates a span element
span.append(elementToAppend)                // Inserts an element into the span
document.querySelector("nav").append(span)  // Adds the span into a nav tag
相关问题