如何在没有 jQuery 的情况下在 JavaScript 中的元素之前插入 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19315948/
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-26 23:39:36  来源:igfitidea点击:

How to insert HTML before element in JavaScript without jQuery?

javascriptjqueryhtmldom

提问by Aymand Osanes

How can I rewrite this jQuery operation in pure JavaScript:

如何在纯 JavaScript 中重写此 jQuery 操作:

$("#my_id").before('<span class="asterisk">*</span>');

回答by Rob W

A little-known method is the element.insertAdjacentHTML. With this method (supported by all major browsers, including IE 4), you can take an arbitrary HTML string, and insert it anywhere in the document.

一个鲜为人知的方法是element.insertAdjacentHTML. 使用此方法(所有主要浏览器都支持,包括IE 4),您可以获取任意 HTML 字符串,并将其插入文档中的任何位置。

To illustrate the power of the method, let's use your example...:

为了说明该方法的强大功能,让我们使用您的示例...:

$("#my_id").before('<span class="asterisk">*</span>');

Becomes

成为

document.getElementById('my_id').insertAdjacentHTML('beforebegin',
    '<span class="asterisk">*</span>');

insertAdjacentHTML's first argument determines the insertion position. Here's a comparison with jQuery:

insertAdjacentHTML的第一个参数确定插入位置。这是与jQuery的比较:

As you can see, it's very easy to use. Assuming that the jQuery selector returns only one element, you can in general use document.querySelector, but in this specific case, using document.getElementByIdis more efficient.

如您所见,它非常易于使用。假设 jQuery 选择器只返回一个元素,您可以在一般document.querySelector情况下使用,但在这种特定情况下,使用document.getElementById效率更高。

回答by Codemonkey

Edit:I prefer @Rob W's answer and think that that should be the accepted answer, not this one.

编辑:我更喜欢@Rob W 的答案,并认为这应该是公认的答案,而不是这个答案。



This will do what you want, without needing the support of any bloated libraries like jQuery.

这会做你想做的,不需要任何像 jQuery 这样臃肿的库的支持。

var my_elem = document.getElementById('my_id');

var span = document.createElement('span');
    span.innerHTML = '*';
    span.className = 'asterisk';

my_elem.parentNode.insertBefore(span, my_elem);

回答by Rohan Kumar

You can make your own function in javascript like,

您可以在 javascript 中创建自己的函数,例如,

Code

代码

var id = document.getElementById('my_id');
var s = document.createElement('span');
s.innerHTML = '*';
s.className = 'asterisk';
id.parentNode.insertBefore(s, id);

InsertBefore Docsand Example

InsertBefore 文档示例

You can create a function beforelike,

你可以喜欢之前创建一个函数,

before: function() {
    return this.domManip( arguments, false, function( elem ) {
        if ( this.parentNode ) {
            this.parentNode.insertBefore( elem, this );
        }
    });
},

source from http://code.jquery.com/jquery-1.9.1.js

来源来自http://code.jquery.com/jquery-1.9.1.js