Preserving single or double quotes around attributes in browser

后端 未结 2 1947
天命终不由人
天命终不由人 2021-01-26 08:40

I want to preserve single or double quotes around html attributes, specifically for innerHTML within the content editable div. I know this is weird requirement, but I am looking

相关标签:
2条回答
  • 2021-01-26 09:14

    Those quotation marks aren't actually in the DOM at all; the DOM is a data structure, with string objects for the attribute values. It doesn't retain any information about whether the strings were single- or double-quoted in the original source, since there's no difference in meaning between the two forms.

    The HTML that you see in Firefox's developer tools is not a copy of your HTML source code; it's generated from the DOM data structure. And since the DOM doesn't include any information about how the strings were quoted in the original source code, the developer tools just quotes them all in a default way when generating new HTML from the DOM.

    0 讨论(0)
  • 2021-01-26 09:17

    HTML is a "carrier of structured information", it itself is not the information. It's like the envelope around a letter. HTML is used to convey the structural information of the desired DOM from your server to the browser. Once the browser receives this information, it "unpacks" it and constructs the DOM. Then it discards the HTML text, because it has no further use for it; it is now working with the DOM data structure.

    There's no place in the DOM for storing what kind of quotes were used to construct a DOM element's attributes. Because it's irrelevant. foo='bar' is 100% equivalent to foo="bar" to foo=bar in terms of expressing an attribute and its value in serialised form. It's always possible to derive a serialised form from the DOM; in other words the DOM can always be written to HTML again from scratch. You can convert HTML → DOM → HTML → DOM → HTML back and forth all day long. However, the specific formatting of the HTML will not stick, because it's irrelevant and gets discarded in the conversion.

    That's what you're seeing in the DOM inspector or in .innerHTML: just a representation of the current DOM expressed in serialised HTML. There's no point in caring about the specific format of that HTML, as long as it expresses the same information. And no, you can't preserve it.

    If you really really want that, you'll have to bend over backwards and do a lot of manual HTML processing.

    0 讨论(0)
提交回复
热议问题