You need to enable JavaScript to run this app. 如何将<div>元素存储到localStorage?取出为等长空对象是什么原因
优惠活动
大模型
产品
解决方案
定价
更多

如何将<div>元素存储到localStorage?取出为等长空对象是什么原因

问题原因与解决方案

你遇到的问题本质是DOM元素无法直接被JSON序列化,这是JSON.stringify的固有特性限制。

  • JSON仅支持序列化纯数据类型(普通对象、数组、字符串、数字、布尔值、null),DOM元素属于浏览器宿主对象,包含大量不可枚举属性、循环引用(比如parentNode和childNodes互相引用)、内置方法,JSON序列化时会直接过滤这些内容,最终只能得到空对象。
  • 你在setItem前打印的items是DOM对象的实时引用,浏览器控制台会完整展示DOM节点结构,但这和JSON序列化的处理逻辑完全无关。

正确实现逻辑

你需要放弃直接存储DOM元素,改为存储生成DOM所需的纯配置数据,读取后再动态生成DOM插入页面:

第一步:改造存储逻辑

先把DOM对应的配置数据提取出来存到数组,再序列化存入localStorage:

// 假设每个div对应的配置数据结构如下,可根据你的需求扩展
const itemsConfig = items.map(div => ({
  text: div.textContent,
  className: div.className,
  style: div.style.cssText,
  id: div.id,
  // 其他你需要保留的自定义属性
}));

function setToLocalStorage(){
  if(localStorage.getItem("items")){
    localStorage.removeItem("items");
  }
  localStorage.setItem("items",JSON.stringify(itemsConfig));
}

第二步:改造读取逻辑

拿到存储的配置数据后,遍历生成DOM元素再插入到页面对应位置:

function getDataFromLocalStorage(){
  const elementsConfig = JSON.parse(localStorage.getItem('items')) || [];
  // 生成DOM元素
  const elements = elementsConfig.map(config => {
    const div = document.createElement('div');
    div.textContent = config.text;
    div.className = config.className;
    div.style.cssText = config.style;
    div.id = config.id;
    // 其他属性赋值
    return div;
  });
  // 此处把生成的elements插入到页面对应容器即可
  // 示例:document.querySelector('.container').append(...elements);
  console.log(elements); // 此时得到的就是可用的DOM元素数组
}

内容的提问来源于stack exchange,提问作者Guilherme Marques dos Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:06:03