I just got into my first edit war. After receiving a suitable moderator scolding in response (and being explicitly instructed to take it to Meta), I'd like Meta's help in resolving it.
Creating a new DOM element from an HTML string using built-in DOM methods or prototype is a question from 2009. Back in 2009, Crescent Fresh posted an answer containing two solutions: one which used Prototype.js, and another that used a trick involving setting the .innerHTML
property of a div
. The full text of that answer, as it was at the end of 2017, is as follows:
Should be obvious, but the link to that MSDN article is regarding an IE only feature.
Generally the following cross-browser trick is what all the libraries do to get DOM elements from an HTML string (with some extra work for IE for
<td>
s,<tr>
s,<thead>
s,<select>
s and more):var s = '<li>text</li>'; // HTML string var div = document.createElement('div'); div.innerHTML = s; var elements = div.childNodes;
Or
var element = div.firstChild
if you know you're getting a single root node.I would recommend you stick to the library-approved method of creating elements from HTML strings though. Prototype has this feature built-into its
update()
method.
This answer is currently accepted and the highest upvoted answer on the question. This solution is slightly flawed, and has been since the time that it was written, since the div
technique doesn't work if you're trying to parse HTML that is illegal as the descendent of a div
, such as a td
element. (Or at least it doesn't reliably work - the details will depend upon browsers' handling of illegal HTML and for all I know it might work for some elements that are illegal as the child of a div
; you'd need to ask somebody with more knowledge of HTML than me. But at least, it doesn't work for td
s.) Additionally, the answer is slightly flawed in that it doesn't note this drawback.
In 2016, I posted an answer noting that the template
element, included in HTML 5, allows you to perform roughly the same trick but without the drawback of failing on td
s, since a template
can legally have any elements as children. I also noted that browser support for template
is incomplete. Note that this means that Crescent Fresh's answer is not yet completely obsolete - you might well want to favour it over mine for browser compatibility reasons.
On December 21st, I edited the question with the goal of making it more concise. Unfortunately, in doing so I removed the MSDN link from it that was being referenced by Crescent Fresh's answer, rendering the first paragraph of his answer nonsensical. My bad; I messed up. Sorry about that.
Yesterday at 16:00 UTC, the first salvo of the edit war is fired, with mikemaccana making a pair of edits that left Crescent Fresh's answer in the following state:
To get DOM elements from an HTML string:
var createElementFromHTML = function(tagString){ var div = document.createElement('div'); div.innerHTML = tagString.trim(); return div.childNodes[0]; }
Assuming
tagString
contains a single parent tag.
There are, in my view, a lot of things wrong with this edit. I rolled it back (taking the opportunity to remove the paragraph I'd rendered incoherent in December while I was at it), and explained why in a comment:
@mikemaccana, your edit removed multiple bits of information from the question: the solution with Prototype; how to do this for a single vs multiple nodes; that this solution is (or rather was) used in popular libraries; and that supporting old IE versions requires some additional work. Even leaving aside that this answer is (and always was) flawed, and that I'd recommend modern readers use mine instead, I don't see any good reason for deleting all of that info, and have accordingly rolled back your edit.
Mike responds:
@MarkAmery My edit fixed the minified code, added a wrapper functions, removed the outdated information regarding versions of IE no longer in popular use, and removed the prototype.js info, as prototype is no longer popular. Thanks for letting me know you rolled it back. I'll make the same fixes again and leave in the information about ancient versions of IE for (both) developers who love IE8 and (all three) developers who love prototype.js in 2018,, not for the benefit of readers, but simply to keep you happy.
(Note that I presume the minified code being referred to is the string named s
in the original version of Crescent's post; all other variables had full English names.)
Upon reading this, I thought we'd come to a compromise, albeit not an entirely amicable one. I voiced my assent:
@mikemaccana "Minified code" seems like a slightly hyperbolic way of saying "most variables have full English names, but there's also a string named s", but sure - I've got no objection to renaming that to
htmlString
.
Unfortunately, this was not where the story ended. Mike's next series of edits left the post as follows:
Using HTML templates (for current browsers - alas no node/JSDOM support at the time of writing):
var createElementFromHTML = function(tagString) { var template = document.createElement('template'); template.innerHTML = html; return template.content.cloneNode(true); }
Using innerHTML (for older browsers and node, but may have issues with some elements - see discussion in other answers:
var createElementFromHTML = function(tagString){ var div = document.createElement('div'); div.innerHTML = tagString.trim(); // You can change this to div.childNodes if you need to handle multiple root elements in your string. return div.firstChild; }
Note: if you are still developing for Internet Explorer in 2018, and target versions of IE more than a decade old: (there is with some extra work to handle bugs in IE 8 and earlier for
<td>
s,<tr>
s,<thead>
s,<select>
s and other elements).Note: if you happen to use prototype.js in 2018, prototype has this feature built-into its
update()
method.
This is a highly flawed attempt at an answer. I noted some of the problems in a comment (though I hadn't seen them all yet), accompanied by a second rollback:
@mikemaccana I've rolled back your edit again, for several reasons: the function at the top was broken in two ways (missing
trim()
and a variable name error), there were a bunch of English errors, the snark about old browsers and libraries was entirely gratuitous, it invalidated a bunch of comments, and more fundamentally it transformed the post into a totally different answer than the one that Crescent Fresh originally posted; I don't think that hijacking an accepted answer to post an entirely different solution is a legit use of editing powers. If you disagree, we can take it to Meta.
Mike didn't share my point of view, and commented to say so. At this point in the exchange, he stopped @-notifying me, so that I had to manually drop in on the question to see if any changes had been made.
Mark: I added '.trim()` to the answer to handle TemplateStrings. Indeed, I forgot to add it to the second answer: perhaps you should have suggested that as a constructive way of giving feedback rather than revert the answer to it's nine year old state. I don't think there was any snark, but the comments only existed because you personally insisted IE8 and prototype.js be left in an answer in 2018. I've undone the vandalism: if you believe that maintaining old answers should be forbidden on StackOverflow, take it to meta yourself.
I voiced some anger:
@mikemaccana Seriously, your response to a rollback in which I @-notified you with a detailed explanation of my reasoning and invited further discussion is to reapply your edit without notifying me? I've mod-flagged. And yes, I think that on a question tagged with
prototypejs
and which explicitly asks about answers using Prototype, the prototype solution shouldn't be scrubbed from the accepted answer. "Maintaining" an answer and replacing it wholesale with a different answer via an edit are not the same thing.
I'll admit that this complaint about radical edits is a tad hypocritical. I've made some seriously radical edits before that absolutely violated both the letter and spirit of many of the editing guidelines established on Meta because I thought they ultimately helped future readers, rules be damned; as such, I probably shouldn't be throwing stones inside my glass house. But my frustration here came from the fact that the main change being made to Crescent's answer was, effectively, to tack on (an inferior version of) my answer, when my answer was already posted and a user dissatisfied with Crescent's could just scroll down to it.
I listed, over the course of 3 comments, the errors in Mike's answer, and my reasons for objecting to his edit. Those comments can now be read in chat. Then I retracted my mod flag, because I thought I saw a path forward that would leave us both happy:
@mikemaccana Hmm. I've cooled my head and retracted my mod flag, because I think we can still probably find a final form for this answer that will satisfy us both. I sympathise with wanting the top answer on the Q to not mislead people; I just don't think that basically duplicating my solution into there is the right way, especially when this post still has upsides over mine (compatibility with older browsers). Unless you object and would rather take this to Meta/mods, after work I'll tweak the answer to note explicitly that (unlike some other approaches) this won't work for some elements, like
td
s, but that it has the advantage of decent support for old browsers. I'll keep all the information - about this (once) being a technique used in library internals, about the Prototype solution, and about the extra work needed to support IE. And then new readers can see up front that this has downsides, and if they want a template-based solution, scroll down to mine. Does that seem reasonable to you?
Mike wasn't having it. Again, without @-notifying me, he replied:
Mark: I've already kept the info about prototype, and old IE, and tds, so I don't understand what work you would be doing by modifying the answer again. I updated the answer with the
template
as that should be preferable, including a link to the official docs with proper link text (unlike your own answer) as that's a reasonable update to a question whose answer has changed. I suggest that the issue is not updating old answers with new info, but a personal one as you have one of the other answers, albeit with less information. So short answer: no. Please don't remove any further work.Mark: I see you've ignored your own promise not to vandalise further unless asked. I've reverted the changes again. Please stop vandalising answers and file a meta issue if you dislike updates to decade old answers.
Here's the latest attempt at a revision from him:
Using HTML templates (for current browsers - alas no node/JSDOM support at the time of writing):
var createElementFromHTML = function(tagString) { var template = document.createElement('template'); template.innerHTML = tagString.trim(); return template.content.cloneNode(true); }
Using innerHTML (for older browsers and node, but may have issues with some elements - see discussion in other answers:
var createElementFromHTML = function(tagString){ var div = document.createElement('div'); div.innerHTML = tagString.trim(); // You can change this to div.childNodes if you need to handle multiple root elements in your string. return div.firstChild; }
Note: if you are still developing for Internet Explorer in 2018, and target versions of IE more than a decade old: (there is with some extra work to handle bugs in IE 8 and earlier for
<td>
s,<tr>
s,<thead>
s,<select>
s and other elements).Note: if you happen to use prototype.js in 2018, prototype has this feature built-into its
update()
method.
Most of the issues that I pointed out in his previous revision remain unfixed. There are a slew of both minor English errors, stylistic issues, and significant technical errors, which I'll enumerate:
- "Node" should be capitalised
- "jsdom" should be all lowercase (see the stylisation in their official docs)
- The first
createElementFromHTML
in fact returns aDocumentFragment
, not an element. This is important because it means that the returned value won't have the properties that you'd expect it to have if it were an element - for instance, the result ofcreateElementFromHTML('<input>')
will have novalue
property. - The
cloneNode(true)
call is unnecessary (since the function's local scope holds the only reference to theDocumentFragment
being cloned) and probably incurs an avoidable (albeit unimportant) performance penalty. - The paragraph between the two code blocks wrongly and confusingly implies that the first code block doesn't use
innerHTML
, when in fact it does. - There's an unclosed left parenthesis in that same paragraph.
- Although the second code block includes a comment suggesting how to tweak the function to handle a HTML string made up of multiple elements, the first does not.
- The answer wrongly claims that its IE-specific errors only apply to IE 8 and below, when according to comments on the answer they in fact apply up to at least IE 10. (I haven't confirmed.)
- The explicit references to 2018 are gonna look pretty silly in 2019 (and come across kind of snarky).
Point 3 in particular is a real showstopper - and I'd pointed it out, explicitly, in the comments, along with several of the other errors here. Despite having had these errors explicitly pointed out to him, Mike just went ahead and reintroduced his edit anyway, knowingly restoring broken content to the post - which it seems to me is, at best, pretty damn sloppy. I rolled back, and then Martijn Pieters arrived on the scene and told us both to knock it off and take it to Meta. So here I am.
In my ideal world, I'd like Crescent Fresh's answer to be modified to read something like this (linking to my answer, as mine links to his):
The following cross-browser trick is what all the libraries used to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of
innerHTML
):var s = '<li>text</li>'; // HTML string var div = document.createElement('div'); div.innerHTML = s; var elements = div.childNodes;
Or
var element = div.firstChild
if you know you're getting a single root node.Note that this won't work for some elements that cannot legally be children of a
div
, such astd
s. However, you might nonetheless prefer this approach over [similar approaches with atemplate
](link to my answer) because it will work in older browsers that do not support thetemplate
element.I would recommend you stick to the library-approved method of creating elements from HTML strings though. Prototype has this feature built-into its
update()
method.
In my view, this would serve readers best - they would have two separate approaches they could vote on separately, the drawbacks of Crescent's approach would be clearly spelt out in his answer, and anyone wanting to use the template
-based approach would get to read about it in my more detailed answer that includes spec links, details about the types and properties involved, and stats from Can I use... about browser support - all useful detail to have before deciding to use the answer - rather than just an unexplained function.
I guess I have several questions:
What final form should Crescent Fresh's answer end up in? Should the
template
-based solution just be lifted from my answer and added to his older one (with the various issues present in mikemaccana's versions fixed), or is that inappropriate? Is my proposal above a good one?How should I have handled this differently? I've definitely voiced some anger and assumed some bad faith that I oughtn't've over the course of the conversation, but there are other questions here. Martijn Pieters is of the view that I should've escalated to the mods at or before the second rollback - at a point when dialog was still ongoing and it still seemed to me like Mike and I might reach an agreement. Does it really make sense to escalate to mods - and Meta - in such circumstances?
I've spent 2 hours writing this post, and frankly I'm a bit angry about having to spend my time on it. More man-hours will be spent reading it. In circumstances outside of rollback wars, we're told that moderators are exception handlers, not to be used in scenarios where we have the power to handle problems ourselves. Isn't this incompatible with escalating rollback wars to mods while dialogue is still ongoing? And am I really meant to burn an hour or hours of my life putting a case to Meta every time I disagree with someone about how a post should look, even when I might still be able to solve it through conversation in the comments with a fraction of the effort?
Leaving aside going to the mods, isn't publicising this sort of dispute on Meta problematic? I did it because Martijn asked me to, and I don't have any other recourse left, but I'm not comfortable with it. I'm basically publicly calling out a user, by name, for making technically incorrect edits to a post after being explicitly informed that the edits contained errors - something which, assuming good faith as far as is possible, indicates some pretty rushed and reckless editing borne out of impatience and frustration at me. Aren't these kind of personal slap-fights meant to be the mods' business, not Meta's?