使用 Javascript 动态创建 HTML 元素?

新手上路,请多包涵

我想动态创建一些 HTML 元素(3 个 html 元素),然后将此 html 代码作为变量中的字符串返回。我不想将以下函数中的 HTML 代码写入某个 div,但是,我想在 var 中返回它。

 function createMyElements(id1,id2,id3){

   //create anchor with id1
   //create div with id 2
   //create xyz with id3

  //now return the html code of above created just now

}

我怎样才能做到这一点?

原文由 dojoX 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 390
1 个回答

[ 编辑 202110 ] 这个答案现在 > 10 岁了。这是一个片段,其中包含几种创建和/或注入元素的方法。问题的答案( _创建一些元素并检索它们的 html 代码_)可以在代码片段的底部找到。

 // The classic createElement
// -------------------------
// create a paragraph element using document.createElement
const elem = document.createElement(`p`);
elem.id = `myBrandnewDiv1`;

// put in some text
elem.appendChild(document.createTextNode(`My brand new div #1`));

// append some html (for demo, preferrably don't use innerHTML)
elem.innerHTML += ` => created using
  <code>document.createElement</code>`;

// append a new paragraph within #myBrandNewDiv1
const nested = elem.appendChild(document.createElement(`p`));
nested.classList.add(`nested`);
// add some text to that
nested.textContent = `I am nested!`;
// the elements are still in memory, now add the
// whole enchillada to the document
document.body.appendChild(elem);

// insertAdjacentHTML
// ------------------
// nest an element within the nested div
nested.insertAdjacentHTML(`afterbegin`,
  `<div id="nestedWithin#nested">
    This text will appear <i>above</i> the text of
    my parent, that being div#nested.
    Someone had the nerve to insert me using
    <code>insertAdjacentHTML</code>
   </div>`);

// Object.assign
// -------------
// Use Object.assign to create an element and
// assign properties/html to it in one go
const newElem = Object.assign(
  document.createElement(`div`),
  { id: `myBrandnewDiv2`,
    innerHTML: `div#myBrandnewDiv2 signing in.
      I was <i>assigned</i> using <code>Object.assign</code>&hellip;`});
document.body.appendChild(newElem);

// insertAdjacentElement combined with Object.assign
// -------------------------------------------------
// use the above technique combined with insertAdjacentElement
newElem.insertAdjacentElement(
  `beforeend`,
    Object.assign(document.createElement(`span`),
      { id: `myBrandnewnested2_nested`,
        innerHTML: `<br>Me too! And appended I was
          with <code>insertAdjacentElement</code>` })
);

// createDocumentFragment
// ----------------------
// Use a document fragment to create/inject html
const fragment = document.createDocumentFragment();
const mdnLnk = `https://developer.mozilla.org/en-US/` +
    `docs/Web/API/Document/createDocumentFragment`;
fragment.appendChild(
  Object.assign(
    document.createElement(`p`),
    {innerHTML: `Regards from <code>createDocumentFragment</code>
    (see <a href="${mdnLnk}">MDN</a>)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);

// Create, but don't inject
// ------------------------
const virtual = Object.assign(
      document.createElement(`p`),
      { innerHTML: `
        <a href="#id1">id1</a>
        <div id="id2">Hi!</div>
        <p id="id3">Hi 2!</p>`,
        classList: [`xyz`], } );

const prepareHtml4Reporting = html =>
  html.replace(/</g, `&lt;`)
    .replace(/\n\s+/g, `\n`)
    .replace(/\n\n/g, `\n`);

document.body.insertAdjacentHTML(
  `beforeend`,
  `<h3>html only</h3><pre>${
     prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
 body {
  font: normal 12px/15px verdana, arial, sans-serif;
  margin: 2rem;
}

code {
  background-color: #eee;
}

.nested {
  margin-left: 0.7rem;
  max-width: 450px;
  padding: 5px;
  border: 1px solid #ccc;
}

我在这个 中使用了其中的一些方法(请参阅 /src/DOM.js ),以及在注入之前清理 html 的机制。

原文由 KooiInc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题