Javascript 使用 jQuery 将一串 HTML 转换为 DOM 对象

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

Convert a string of HTML into DOM objects with jQuery

javascriptjquerydom

提问by Vineel Kumar Reddy

I have HTML in a JavaScript string (containing usual, nested HTML). Using jQuery, can I convert that into a valid HTML element in a single stroke using any of the document.create* functions? My requirement is to use document.getElementByIdon the created DOM object.

我在 JavaScript 字符串中有 HTML(包含通常的嵌套 HTML)。使用 jQuery,我可以使用任何document.create* 函数在一次笔划中将其转换为有效的 HTML 元素吗?我的要求是document.getElementById在创建的 DOM 对象上使用。

回答by P K

Take simple nested example.

以简单的嵌套示例为例。

var dom_string = '<div>xxx<div>yyy</div></div>';

create HTML DOM elements using $() function of jquery and append wherever you want. i have taken 'body' but you can append anywhere.

使用 jquery 的 $() 函数创建 HTML DOM 元素并附加到任何你想要的地方。我已经采取了“身体”,但你可以在任何地方附加。

$(dom_string).appendTo('body');

Alternatively you can implement this with pure javascript:

或者,您可以使用纯 javascript 来实现:

var dom_target = document.getElementById("target");
dom_target.innerHTML = dom_string;

回答by SLaks

Create a dummy element and set its innerHTMLto your HTML string.

创建一个虚拟元素并将其设置innerHTML为您的 HTML 字符串。

回答by David Rivers

// Construct a container as a placeholder for your content

var container = document.createElement('div');
container.id = 'container';

// Inject the container into the DOM

document.body.appendChild(container);

// Populate the injected container with your content

container.innerHtml = '<p id="pTag">I am a <em>P</em> tag with some <strong>nested markup</strong>.</p>';

回答by Theo

To convert Html text into a Jquery-Object use the $() function:

要将 Html 文本转换为 Jquery 对象,请使用 $() 函数:

div = '<div>hello world</div>';
$div = $(div);

But as others have noted in most cases you don't need that because DOM manipulation functions like append() and prepend() will accept plain text, so

但正如其他人所指出的,在大多数情况下你不需要它,因为像 append() 和 prepend() 这样的 DOM 操作函数将接受纯文本,所以

$('body').append('<div>hello world</div>');

is absolutely fine.

绝对没问题。