Pregunta

In Dart I'm trying to add HTML dynamically in a div element.

Note: the mainContainer element is just a div in my HTML code

import 'dart:html';

main()
{ 
  loadHTML("web/html/test.html");
}

void loadHTML(String fileName) 
{
  DivElement div = query("#mainContainer");
  div.children.clear();

  HttpRequest.getString(fileName).then((resp) {
    div.appendHtml(resp);
  });
}

Here is the test.html just for testing purposes

<h1 id="test">test</h1>

The problem is when I want to query for #test it will not find anything

...
main()
{ 
  loadHTML("web/html/test.html");

  Element elem = query("#test");
  if (elem == null)
  {
    print("element is null");
  }
}
...

Is it because the HTML isn't loaded into the document yet? I'm not sure what is going on here. The actual HTML shows up in the browser however it cannot find test.

Using Dart SDK version 0.5.5.0_r22416

¿Fue útil?

Solución

The way your code is currently organized, you're querying for #test before the the HTML fragment has been appended to the div. If you do the stuff requiring #test in the callback, things should work:

HttpRequest.getString(fileName).then((resp) {
  div.appendHtml(resp);
  Element elem = query("#test");
  if (elem == null)
    print("element is null");
});

If it's not clear to you what's going on, your HttpRequest is asynchronous. This is as it should be (you don't want to block while you wait on the network), but your code needs to account for this; you can't expect the fetched HTML to have been added to the page just because loadHTML() has returned.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top