javascript - .innerHTML 丢失 HTML 语法格式

标签 javascript dom html-parsing

我刚刚注意到浏览器忽略了 HTML 格式(例如对齐此代码段中的两个属性):

 <div id="container">
      <div id="contained"
           other-prop="some value">
      </div>
 </div>

如果你跑

var container = document.getElementById('container');
console.log(container.innerHTML);

你得到输出

<div id="contained" other-prop="some value">
</div>

无论它在源代码中是如何编写的,或者即使您直接在 JavaScript 中设置 .innerHTML 也没有关系。

是否可以查询用户在JS中写的某个元素对应的页面源?有空白和一切。当用户使用 DOM 操作修改元素时,我可以看到存在问题,在这种情况下,如果

  1. 所有未修改的内容都保留原始用户格式,或者
  2. 可以获取用户在页面加载时编写的原始源代码,无需 DOM 修改

一个片段,您可以看到它的实际效果:

var container = document.getElementById('container');
console.log(container.innerHTML);

container.innerHTML = `  
  <div id="contained"
       other-prop="some value">
  </div>
`;

console.log(container.innerHTML);

container.children[0].setAttribute('modification', '');

console.log(container.innerHTML);
<div id="container">
  <div id="contained"
       other-prop="some value">
  </div>
</div>

最佳答案

根本不可能。 将代码视为计算机之间用于表达视觉表示的消息,其中空格并不重要。

关于javascript - .innerHTML 丢失 HTML 语法格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57630710/

相关文章:

使用 if/else 语句与两个不同选择器调用时的 jquery 性能

javascript - 解析从 BeautifulSoup 返回的 JavaScript

python - 使用bs4提取html文件中的文本

php - 如何使用 php/ajax 在指定的 div 中附加附加数据

javascript - Firefox 将 flash 对象缩小到 14px,chrome 和 IE 都很好

javascript - 移动模式下的文本无法 self 修复

javascript - 在 Javascript 事件 DOM 中禁用函数

javascript - 在 JavaScript 中是否有可能获得对唯一 DOM 元素的唯一引用(用作对象中的唯一键)?

Java - 彩票统计解析器

javascript - 破折号案例(Kebab 案例) Angular 2 中的数据绑定(bind)