html: fix wrong comparison in foster parenting algorithm

Fixes golang/go#23071

Change-Id: I383e13bfd87e32ffb775dff54c46b66b090e5017
Reviewed-on: https://go-review.googlesource.com/131475
Run-TryBot: Kunpei Sakai <namusyaka@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Nigel Tao <nigeltao@golang.org>
diff --git a/html/parse.go b/html/parse.go
index bbe0116..4b1fa42 100644
--- a/html/parse.go
+++ b/html/parse.go
@@ -255,7 +255,7 @@
 		}
 	}
 
-	if template != nil && (table == nil || j < i) {
+	if template != nil && (table == nil || j > i) {
 		template.AppendChild(n)
 		return
 	}
diff --git a/html/parse_test.go b/html/parse_test.go
index 0b72a12..1c232c7 100644
--- a/html/parse_test.go
+++ b/html/parse_test.go
@@ -329,6 +329,7 @@
 	`<a href="blah">aba<table><a href="foo">br<tr><td></td></tr>x</table>aoe`: true,
 	`<a><table><a></table><p><a><div><a>`:                                     true,
 	`<a><table><td><a><table></table><a></tr><a></table><a>`:                  true,
+	`<template><a><table><a>`:                                                 true,
 	// A similar reparenting situation involving <nobr>:
 	`<!DOCTYPE html><body><b><nobr>1<table><nobr></b><i><nobr>2<nobr></i>3`: true,
 	// A <plaintext> element is reparented, putting it before a table.
diff --git a/html/testdata/webkit/template.dat b/html/testdata/webkit/template.dat
index 1febfe5..ff822b0 100644
--- a/html/testdata/webkit/template.dat
+++ b/html/testdata/webkit/template.dat
@@ -1131,6 +1131,20 @@
 |   <body>
 
 #data
+<template><template><table>Foo
+#errors
+#document
+| <html>
+|   <head>
+|     <template>
+|       content
+|         <template>
+|           content
+|             "Foo"
+|             <table>
+|   <body>
+
+#data
 <template><template><frame>
 #errors
 #document
@@ -1297,3 +1311,16 @@
 |       content
 |         "Foo"
 |   <body>
+
+#data
+<template><a><table><a>
+#errors
+#document
+| <html>
+|   <head>
+|     <template>
+|       content
+|         <a>
+|           <a>
+|           <table>
+|   <body>