1

I have a problem to insert html into document using javascript.

Code that trying to insert html into document:

function loadTaskPage(taskId){
    fetch("https://localhost:44321/api/Tasks/1")
    .then(function(response){
        return response.text();
    }).then(function(data){
        document.body.insertAdjacentHTML('beforeend', data);
    }).catch(function(error){
        alert(error);
    })
}

This code part I took from tutorial, source code of tutorial could be found in this link: https://github.com/bstavroulakis/progressive-web-apps/blob/master/car-deals/js/carService.js

If I will try to open this link https://localhost:44321/api/Tasks/1 in browser I receive normally styled web page, but when I try to insert it to document, html code got escaped and don't display anything.

Inserted html looks like:

<div id="\"myModal\"" class="\"modal" fade\"="">...

The code below is bootstrap modal copied from code examples. As you see there appeared symbols \" that escapes quotes.

Response with html I receive from my ASP.Net Web Api with header: text/html

How should I insert this html code into document using javascript?

ekad
  • 14,436
  • 26
  • 44
  • 46
Mik
  • 151
  • 3
  • 4
  • 14
  • Similar to [How to add content to html body using javascript](https://stackoverflow.com/questions/13495010/how-to-add-content-to-html-body-using-javascript) – Patrick Barr Jul 26 '17 at 15:44
  • I have try to append `document.getElementById('main-content').innerHTML += data;` like this. But still there appears only text without any styles and still as I said in a ticket all class attributes are escaped. – Mik Jul 26 '17 at 15:57
  • It looks like the escaping in your html is off: there are too many `"`, your html string should be `"
    ..."` otherwise the string inside `id` is `'"id"'` [see this fiddle](https://jsfiddle.net/u0Lzvq9p/)
    – Patrick Barr Jul 26 '17 at 16:14
  • note when I mentioned "the string inside `id`..." I meant that as an example, it's happening in more places than just the `id` – Patrick Barr Jul 26 '17 at 16:20
  • I have added a comment under answer, where I said that I have no idea why there appear additional quotes. my response string is: `
    ` like this.
    – Mik Jul 26 '17 at 18:07

3 Answers3

3

How to insert html to document using javascript?

You can find that answer here:

You can use

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

or

document.getElementById("parentID").innerHTML+= "new content"

As mentioned in the comments, this didn't seem to work and left the elements without style, this is because the escaping in the string being added to the innerHTML is off: there are too many ".

In the provided HTML example <div id="\"myModal\"" class="\"modal" fade\"="">... each attribute is surrounded by "\" ... \"" which means that if you were to look at the string of the attribute's value it would look something like '" ... "', which is what is causing the styles to not be added.

If you remove the extra " the HTML should be appended as expected:

<div id=\"myModal\" class=\"modal fade\">...

See this example showing what happens with the different escaping:

document.getElementById("foo").innerHTML += '<div class="\"bar\"">Hello World!</div>'; // Escaped with too many `"`
document.getElementById("foo").innerHTML += '<div class=\"bar\">Hello World!</div>'; // Properly escaped
.bar {
  color: red;
}
<div id="foo">

</div>
Patrick Barr
  • 1,123
  • 7
  • 17
  • That the point, I didn't said that in ticket, in ASP.Net api I return response content like this: `
    ` and I don't understand why there appear more quotes...
    – Mik Jul 26 '17 at 18:06
1

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

iMath
  • 2,326
  • 2
  • 43
  • 75
0

Ok, looks like problem was in api service. In some reasons in debug mode showed to me correct html that I return to user. So after a few changes of api code all works as should.

If someone interested in ASP.Net Web API how to return view as a string and be able to add it to html all you need is to add Reference to RazorEngine and use the following code:

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        var viewPath = HttpContext.Current.Server.MapPath(@"~/Views/Tasks/TaskDetails.cshtml");
        var template = File.ReadAllText(viewPath);

        var key = new NameOnlyTemplateKey("TaskDetails", ResolveType.Global, null);
        if(!Engine.Razor.IsTemplateCached(key, null))
            Engine.Razor.AddTemplate(key, new LoadedTemplateSource(template));

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        Engine.Razor.RunCompile(key, sw, null, model);

        response.Content = new StringContent(sb.ToString());

        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

        return response;

P.S. Code is not completely correct. It requires some optimizations.

Mik
  • 151
  • 3
  • 4
  • 14