You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多行HTML文本转为DOM对象并跨文件添加至地铁站列表?

解决TypeError: Node.appendChild: Argument 1 is not an object错误

错误原因

localStorage只能存储字符串类型的数据,所以你在脚本A里存进去的是HTML文本字符串,脚本B里取出来的自然也是字符串。但appendChild()方法要求传入的必须是DOM对象,不是纯文本,所以触发了这个错误。

两种解决方法

方法1:用innerHTML直接插入HTML文本

修改脚本B的代码,直接通过innerHTML把HTML文本追加到列表中:

const stationList = document.querySelector('#stations-list')
const newStationHtml = localStorage.getItem('new-list-item')
stationList.innerHTML += newStationHtml

这种方式最简单,适合只需要插入静态HTML的场景。

方法2:将HTML文本转为DOM对象后再添加

如果后续需要对新地铁站元素做DOM操作(比如绑定事件、修改样式),可以先把HTML文本转换成DOM对象,再用appendChild()添加:

const stationList = document.querySelector('#stations-list')
const newStationHtml = localStorage.getItem('new-list-item')

// 创建临时div容器解析HTML文本
const tempContainer = document.createElement('div')
tempContainer.innerHTML = newStationHtml.trim() // 去除多余空白字符

// 取出解析后的li元素
const newStationElement = tempContainer.firstElementChild

// 添加到列表中
stationList.appendChild(newStationElement)

额外提示

如果脚本A里的createHtml函数返回的是DOM对象而非字符串,需要先把它转成HTML字符串再存到localStorage:

const createdElement = createHtml(/* ... */)
const elementHtml = createdElement.outerHTML
localStorage.setItem('new-list-item', elementHtml)

内容的提问来源于stack exchange,提问作者Felix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:27:08