You don't append tags with jquery, you append nodes. The document you are operating on is not a string like <html><head><title>T</title></head><body><div id="D"><p>P</p></div></body></html>
. It is a tree like
HTML Element
+---HEAD Element
| `---TITLE Element
| `---Text node, contents: "T"
`---BODY Element
`---DIV Element, attributes: "id" => "D"
`---P Element
`---Text node, contents: "P"
There is no way to represent an "unclosed tag" or "unfinished element" in the tree. Only complete elements can exist.
The old document.write
method operates on the document as a string, and it can append arbitrary fragments, but there are significant disadvantages to its use. The transition from DOM-level-0 "tag thinking" to modern DOM "tree thinking" is a prerequisite for using jquery.
You need to decide how you want the tree to look in the interval between the time when the start tag is added and the time when the end tag is added. Here's one possible answer: let the implicit closing tag be added, and then rebuild the string from the start each time you append, like this:
$(".somediv").html(wordArray.slice(0,i+1).join(" "));
That way if wordArray
is ["foo","<p>","bar","baz","</p>","quux"]
the loop will work like this:
i string passed to html() equivalent HTML with all tags shown
0 "foo" "foo"
1 "foo <p>" "foo<p></p>"
2 "foo <p> bar" "foo<p>bar</p>"
3 "foo <p> bar baz" "foo<p>bar baz</p>"
4 "foo <p> bar baz </p>" "foo<p>bar baz</p>"
5 "foo <p> bar baz </p> quux" "foo<p>bar baz</p>quux"
Note that when the </p>
from your input gets added, it has no effect. And the addition of the <p>
doesn't have much visible effect either. So maybe it would be better if every element of wordArray
included some text: ["foo","<p>bar","baz</p>","quux"]
It looks a little kludgy, but that's what you get for trying to use incomplete HTML elements as your input format! Tree thinking! For the future!
tags are also automatically closed by
. And that's what I wanted to avoid. – Michael Feb 02 '14 at 08:12