将 HTML 字符串转换为 DOM 元素?

问题描述 投票:0回答:10

有没有办法转换 HTML:

<div>
<a href="#"></a>
<span></span>
</div>

或任何其他 HTML 字符串插入 DOM 元素? (这样我就可以使用appendChild())。我知道我可以执行 .innerHTML 和 .innerText,但这不是我想要的——我确实希望能够将动态 HTML 字符串转换为 DOM 元素,以便我可以在 .appendChild() 中传递它。

更新:似乎有些混乱。我将 HTML 内容放在字符串中,作为 JavaScript 中变量的值。文档中没有 HTML 内容。

javascript html dom
10个回答
524
投票

您可以使用

DOMParser
,如下所示:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link


267
投票

您通常会创建一个临时父元素,可以在其中写入

innerHTML
,然后提取内容:

var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
var div= wrapper.firstChild;

如果您拥有的外部 HTML 元素是一个简单的

<div>
,就像这里一样,这很容易。如果它可能是其他无法随处携带的东西,那么您可能会遇到更多问题。例如,如果它是
<li>
,则您必须让父包装器成为
<ul>

但是 IE 无法在

innerHTML
这样的元素上写入
<tr>
,因此如果您有
<td>
,则必须将整个 HTML 字符串包装在
<table><tbody><tr>
...
</tr></tbody></table>
中,将 that 写入
innerHTML
并从下面几个级别中提取您想要的实际
<td>


87
投票

为什么不使用insertAdjacentHTML

例如:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

17
投票

查看 John Resig 的 纯 JavaScript HTML 解析器

编辑:如果您希望浏览器为您解析 HTML,

innerHTML
正是您想要的。来自这个问题

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;

6
投票

好吧,在我不得不思考其他人的答案之后,我自己意识到了答案。 :P

var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);

2
投票

这里有一些有用的代码。

var uiHelper = function () {

var htmls = {};

var getHTML = function (url) {
                /// <summary>Returns HTML in a string format</summary>
                /// <param name="url" type="string">The url to the file with the HTML</param>

    if (!htmls[url])
    {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    htmls[url] = xmlhttp.responseText;
     };
     return htmls[url];
    };

        return {
            getHTML: getHTML
        };
}();

--将 HTML 字符串转换为 DOM 元素

String.prototype.toDomElement = function () {

        var wrapper = document.createElement('div');
        wrapper.innerHTML = this;
        var df= document.createDocumentFragment();
        return df.addChilds(wrapper.children);
};

--原型助手

HTMLElement.prototype.addChilds = function (newChilds) {
        /// <summary>Add an array of child elements</summary>
        /// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
        /// <returns type="this" />
        for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
        return this;
};

--用法

 thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();

1
投票

只需给元素一个

id
并正常处理即可,例如:

<div id="dv">
<a href="#"></a>
<span></span>
</div>

现在你可以这样做:

var div = document.getElementById('dv');
div.appendChild(......);

或者使用 jQuery:

$('#dv').get(0).appendChild(........);

1
投票

你可以这样做:

String.prototype.toDOM=function(){
  var d=document
     ,i
     ,a=d.createElement("div")
     ,b=d.createDocumentFragment();
  a.innerHTML=this;
  while(i=a.firstChild)b.appendChild(i);
  return b;
};

var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);

0
投票

夏天:

  1. 制作一个不可见的元素
  2. 添加 HTML
  3. 通过获取它的第一个子元素来获取元素

function txtToElem(txt){
let a = document.createElement('div')
a.style.display='none'
document.body.appendChild(a)
a.innerHTML=txt
let b = a.children
document.body.removeChild(a)
return b
}

let htmltext='<span>hello sir</span>'
console.log(txtToElem(htmltext))
//testing that it works as an elem:
document.body.appendChild(txtToElem(htmltext)[0])
<h1>the rest of the website...</h1>

首先,在文档中附加一个 div,通过使用

hide
css 属性使其不可见。

然后,使用

appendChild()

将文本附加到不可见的 div 中

最后,使用

Element.children
属性

获取不可见 div 内的元素

注:

a.children
替换为
a.childnodes
也可以获得嵌套元素

缺点:

  1. 仅适用于前端应用程序

0
投票
const publishButton = document.getElementById("btn-publish");
const titleInput = document.getElementById("title-input");
const contentInput = document.getElementById("content-input");
const messageContainer = document.getElementById("message-container");
const imageInput = document.getElementById("file-input");

publishButton.addEventListener("click", function () {
  // Clear previous messages
  messageContainer.innerHTML = "";

  if (!titleInput.value.trim()) {
    showMessage("Title is required", "text-danger");
  } else if (!contentInput.value.trim()) {
    showMessage("Content is required", "text-danger");
  } else if (!imageInput.files[0]) {
    showMessage("Image is required", "text-danger");
  } else {
    const file = imageInput.files[0];
    const reader = new FileReader();

    reader.onloadend = function () {
      const base64Image = reader.result;

      fetch("https://66e7e6b3b17821a9d9da6ff8.mockapi.io/login", {
        method: "POST",
        body: JSON.stringify({
          title: titleInput.value,
          content: contentInput.value,
          image: base64Image,
        }),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => {
          if (!response.ok) throw new Error("Network response was not ok.");
          return response.json();
        })
        .then((data) => {
          showMessage("Blog post created successfully", "text-success");
          titleInput.value = "";
          contentInput.value = "";
          imageInput.value = "";
          fetchPosts(); // Refresh posts after a successful publish
        })
        .catch((error) => {
          showMessage("There was a problem with the fetch operation.", "text-danger");
          console.error("There was a problem with the fetch operation:", error);
        });
    };

    reader.readAsDataURL(file); // Converts file to base64 string
  }
});

function showMessage(message, className) {
  const p = document.createElement("p");
  p.textContent = message;
  p.className = className;
  messageContainer.appendChild(p);
}

function fetchPosts() {
  let container = document.getElementById("container");

  fetch("https://66e7e6b3b17821a9d9da6ff8.mockapi.io/login")
    .then((response) => {
      if (!response.ok) throw new Error("Network response was not ok.");
      return response.json();
    })
    .then((data) => {
      container.innerHTML = ""; // Clear previous posts
      data.forEach((blog) => {
        if (blog.title || blog.content) {
          let card = document.createElement("div");
          let cardBody = document.createElement("div");
          let title = document.createElement("h2");
          let content = document.createElement("p");
          let deleteButton = document.createElement("button");
          let image = document.createElement("img");

          card.classList.add("card", "mb-3", "w-25", "text-center");
          cardBody.classList.add("card-body");
          title.classList.add("card-title");
          content.classList.add("card-text");
          deleteButton.classList.add("btn", "btn-danger");
          deleteButton.textContent = "Delete";

          image.src = blog.image; // Set the image source
          image.classList.add("card-img-top");
          image.alt = "Image";
          card.appendChild(image);

          title.textContent = blog.title;
          content.textContent = blog.content;

          cardBody.appendChild(title);
          cardBody.appendChild(content);
          cardBody.appendChild(deleteButton);
          card.appendChild(cardBody);
          container.appendChild(card);

          deleteButton.addEventListener("click", function () {
            fetch(
              `https://66e7e6b3b17821a9d9da6ff8.mockapi.io/login/${blog.id}`,
              {
                method: "DELETE",
              }
            )
              .then((response) => {
                if (!response.ok) throw new Error("Network response was not ok.");
                return response.json();
              })
              .then((data) => {
                showMessage("Blog post deleted successfully", "text-success");
                fetchPosts(); // Refresh posts after a successful delete
              })
              .catch((error) => {
                showMessage("There was a problem with the fetch operation.", "text-danger");
                console.error("There was a problem with the fetch operation:", error);
              });
          });
        }
      });
    })
    .catch((error) => {
      showMessage("There was a problem with the fetch operation.", "text-danger");
      console.error("There was a problem with the fetch operation:", error);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.