我有一堆 HTML 列表项,我想要的是能够读取列表项的文本,然后能够让用户能够修改它。每个列表项的结构是相同的:
<li id='1' class='attachment'>
<a href='link.html'>TEXT VALUE I WANT TO READ AND MODIFY</a>
<a href='link2.html'><img src'img1.jpg'></a>
<a href='link3.html'><img src'img2.jpg'></a>
</li>
目前我可以使用
获取列表项li = document.getElementById(id);
但是如果我让它打印出类似的东西
li.childNodes[?]
li.childNodes[?].data
li.childNodes[?].nodeValue etc...
我永远无法让它打印“我想阅读和修改的文本值”,它总是给出 null、undefined 或 [object Text] 或类似的东西。任何帮助将不胜感激。
最佳答案
您需要获取 textContent 或 innerText 属性:
var li = document.getElementById(id);
var t = "textContent" in li.childNodes[0] ? "textContent" : "innerText";
alert(li.childNodes[0][t]);
innerText 由 IE 实现,textContent 由符合标准的浏览器实现。
或者,如果您确定该元素的第一个子节点将是一个文本节点,您可以使用
alert(li.childNodes[0].childNodes[0].nodeValue);
根据您在下面的评论,我们可以安全地假设空白会干扰您示例中的 childNodes 属性。这是正常的 - childNodes 返回作为给定元素的直接后代的元素和文本节点。另一种方法是在较新的浏览器中使用 children:
// 1st example using `children` instead
var li = document.getElementById(id);
var t = "textContent" in li ? "textContent" : "innerText";
alert(li.children[0][t]);
// 2nd example using `children` instead
alert(li.children[0].childNodes[0].nodeValue);
children 在 Firefox 3.5 之前和其他旧版浏览器中不受支持。您可以使用 li.getElementsByTagName("a") 作为您发布的示例 - 但请记住,它将返回所有 元素后代,而不是只是直系子女。
关于javascript - 获取列表项中的文本并使用javascript对其进行修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804009/