使用Alert()显示实际的HTML代码

Using Alert() to display actual HTML code

本文关键字:HTML 代码 显示 Alert 使用      更新时间:2024-05-25

有没有办法使用alert()或其他弹出窗口来显示实际的HTML代码?例如,我有下面的代码:

    var range = selection.getRangeAt(0); 
    var newNode = document.createElement('span');
    newNode.setAttribute("class", "selectedText");
    range.surroundContents(newNode);

我想使用警报来显示的HTML结果

range.surroundContents(newNode);

它应该显示类似的东西

<span class='selectedText'>'range will go in here'</span>.

这就是我想要验证的。谢谢

您可以将html分配给一个变量&提醒可变

HTML

<span class='selectedText' id ="someId">range will go in here</span>

JS

var a = document.getElementById("someId").outerHTML;
alert(a)

工作示例

您可以使用jQuery设置元素的text属性。

var htmlstring = "<span class='selectedText'>'range will go in here'</span>"
$("div.selectedText").text(htmlstring);
var htmlescaped = $("<div>").text(htmlstring).html();

那里的块将以字符串&lt;span class='selectedText'&gt;'range will go in here'&lt;/span&gt;结束,这是html的转义版本,可以以任何方式打印。

请注意,此方法可能会遇到换行符('n)和某些类型的空白的困难。

来源。