jQuery – 變換標籤元素並保持所有屬性

透過 replaceWith() 只能做到替換 HTML 標籤名稱,但是屬性例如 class 那是不會相對替換過去。所以需要透過 callback 這麼寫

$(function (){
     $("body").on("click", ".replace", function (){
          $(this).replaceWith(function (){
               $ele = $("<p>", {
                    html: $(this).html()
               })
               
               $.each(this.attributes, function (key, attribute){
                    $ele.attr(attribute.name, attribute.value)
               })
               
               return $ele
          })
     })
})

我們看範例,當點選 <div> 以後會被替換成 <p>,而且所有屬性都搬移過去。可以打開檢視元素查看。

發表迴響