1

Is there a way to use alert() or another pop-up to display actual HTML code that? For example, I have the code below:

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

I want to use an alert to display the HTML result of

range.surroundContents(newNode);

It should display something like

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

Which is what I want to validate.Thanks!

DRE
  • 29
  • 4

2 Answers2

0

You can assign the html to a variable & alert that variable

HTML

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

JS

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

Working Example

brk
  • 48,835
  • 10
  • 56
  • 78
0

You can use jQuery to set the element's textproperty.

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

That block there will end up with the string &lt;span class='selectedText'&gt;'range will go in here'&lt;/span&gt;, which is an escaped version of your html, which can be printed any way you like.

Note that this method may encounter difficulties with newlines (\n) and some types of whitespace.

Source.

Community
  • 1
  • 1
kirkpatt
  • 625
  • 5
  • 21