Javascript JQuery 附加的 JS DOM 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10318294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:49:55  来源:igfitidea点击:

JS DOM equivalent for JQuery append

javascriptjquerydom

提问by Battery

What is the standard DOM equivalent for JQuery

什么是 JQuery 的标准 DOM 等价物

element.append("<ul><li><a href='url'></li></ul>")?

element.append("<ul><li><a href='url'></li></ul>")?

回答by Tobias Krogh

I think you have to extend the innerHTML property to do this

我认为你必须扩展 innerHTML 属性才能做到这一点

element[0].innerHTML += "<ul><li><a href='url'></a></li></ul>";

some explanation:

一些解释:

  • [0] needed because elementis a collection
  • += extend the innerHTML and do not overwrite
  • closing </a>needed as some browsers only allow valid html to be set to innerHTML
  • [0] 需要,因为element是一个集合
  • += 扩展 innerHTML 并且不覆盖
  • </a>需要关闭,因为某些浏览器只允许将有效的 html 设置为 innerHTML

回答by Ry-

Use DOM manipulations, not HTML:

使用 DOM 操作,而不是 HTML:

let element = document.getElementById('element');

let list = element.appendChild(document.createElement('ul'));
let item = list.appendChild(document.createElement('li'));
let link = item.appendChild(document.createElement('a'));

link.href = 'https://example.com/';
link.textContent = 'Hello, world';
<div id="element"></div>

This has the important advantage of not recreating the nodes of existing content, which would remove any event listeners attached to them, for example.

这具有不重新创建现有内容的节点的重要优势,例如,这将删除附加到它们的任何事件侦听器。

回答by M_R_K

Proper and easiest way to replicate JQuery append method in pure JavaScript is with "insertAdjacentHTML"

在纯 JavaScript 中复制 JQuery append 方法的正确和最简单的方法是使用“insertAdjacentHTML”

    var this_div = document.getElementById('your_element_id');
    this_div.insertAdjacentHTML('beforeend','<b>Any Content</b>');

More Info - MDN insertAdjacentHTML

更多信息 - MDN insertAdjacentHTML

回答by gdoron is supporting Monica

from the jQuery source code:

来自 jQuery 源代码:

append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 ) {
            this.appendChild( elem ); //<====
        }
    });
},

Note that in order to make it work you need to construct the DOM element from the string, it's being done with jQuery domManipfunction.

请注意,为了使其工作,您需要从字符串构造 DOM 元素,这是使用 jQuerydomManip函数完成的。

jQuery 1.7.2 source code

jQuery 1.7.2源代码

回答by Tom

element.innerHTML += "<ul><li><a href='url'></li></ul>";