15

I'm trying to use HTML Agility Pack to append a script element into the top of the HEAD section of my html. The examples I have seen so far just use the AppendChild(element) method to accomplish this. I need the script that I am appending to the head section to come before some other scripts. How can I specify this?

Here's what I'm trying:

HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.Load(filePath);
HtmlNode head = htmlDocument.DocumentNode.SelectSingleNode("/html/head");
HtmlNode stateScript = htmlDocument.CreateElement("script");
head.AppendChild(stateScript);
stateScript.SetAttributeValue("id", "applicationState");
stateScript.InnerHtml = "'{\"uid\":\"testUser\"}'";

I would like a script tag to be added toward the top of HEAD rather than appended at the end.

Sam
  • 7,252
  • 16
  • 46
  • 65
Nick
  • 19,198
  • 51
  • 185
  • 312
  • 1
    Sidenote to others finding this question: `stateScript.InnerHtml=...` will sometimes do weird stuff to your javascript. To work around this you can instead do `stateScript.AppendChild(htmlDocument.CreateTextNode(scriptText));` – jp36 Apr 02 '12 at 16:11

2 Answers2

19

Realizing that this is an old question, there is also the possibility of prepending child elements that might not have existed then.

// Load content as new Html document
HtmlDocument html = new HtmlDocument();
html.LoadHtml(oldContent);

// Wrapper acts as a root element
string newContent = "<div>" + someHtml + "</div>";

// Create new node from newcontent
HtmlNode newNode = HtmlNode.CreateNode(newContent);

// Get body node
HtmlNode body = html.DocumentNode.SelectSingleNode("//body");

// Add new node as first child of body
body.PrependChild(newNode);

// Get contents with new node
string contents = html.DocumentNode.InnerHtml;
Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100
7

Got it..

HtmlNode has the following methods:

HtmlNode.InsertBefore(node, refNode)
HtmlNode.InsertAfter(nodeToAdd, refNode)
Oleks
  • 31,955
  • 11
  • 77
  • 132
Nick
  • 19,198
  • 51
  • 185
  • 312
  • Be careful when modifying HTML source. It can change other parts of the HTML code that maybe you don't want to touch `:/` – Oscar Mederos May 18 '11 at 08:01