Markus
Markus

Reputation: 3353

How to wrap an HtmlElement in an HtmlDocument

Is it possible to wrap an HtmlElement with another HtmlElement? And if so, how?

Lets say, I have this HTML, and I want to wrap the img with an additional div:

<html>
  <head><title>foo</title></head>
  <body>
    <img src="test.png"/>
    <p>Hello World</p>
  </body>
</html>

I've tried using following snippet (n.b. document element is an HtmlDocument):

$htmlFile = New-Object -ComObject "HTMLFile"
$htmlFile.IHtmlDocument2_write((gc -Path "./html.htm" -Raw))
$htmlFile.documentElement.getElementsByTagName("img") | %{
  $div = $htmlFile.createElement("div")
  $div.className += "nonbreakingImage"
  $void = $div.appendChild($_)
  $_.OuterHtml = $div.OuterHtml
}

But this, unfortunately, just removes the image tag:

<BODY><P>Hello World</P></BODY>

Another Idea was, to do something like this:

$htmlFile = New-Object -ComObject "HTMLFile"
$htmlFile.IHtmlDocument2_write((gc -Path "./html.htm" -Raw))
$htmlFile.documentElement.getElementsByTagName("img") | %{
  $parent = $_.parentNode
  $void = $parent.removeChild($_)
  $div = $parent.appendChild($htmlFile.createElement("div"))
  $div.className += " nonbreakingImage"
  $void = $div.appendChild($_)
}

But that leaves me with a wrong child order:

<BODY>
  <P>Hello World</P>
  <DIV class=" nonbreakingImage"><IMG src="test.png"></DIV>
</BODY>

Any ideas and hints are welcome!

Upvotes: 1

Views: 183

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67148

You can replace <img> node with a <div> node then add (now floating) <img> node to newly added <div>. In code:

$htmlFile.documentElement.getElementsByTagName("img") | %{
  $div = $htmlFile.createElement("div")
  $div.className += " nonbreakingImage"

  $_.parentNode.replaceChild($div, $_)
  $div.appendChild($_)
}

In alternative you may $_.insertBefore($div, ...) of node obtained by $_.previousSibling(...) but it's longer.

Upvotes: 2

Related Questions