问题:我有一个包含元素的列表,我想将所有列表元素的总和添加到 h1 元素。
我正在尝试通过 javascript 添加额外的 html 来做到这一点。您可以在这 10 行 js 代码中看到这一点。
第一个 console.log(newHeading.textContent) 返回“undefined”。这是为什么?那是因为我没有创建一个单独的 em-Element 作为文本的父节点(这只是列表项的相应总和)?
第二个 console.log 返回标题 + html + 元素总和,即使我使用了 text.Content。这是为什么?
这是到目前为止的样子:Codepen
/* add item-counter to header
*
*/
var heading = document.getElementById("title"); // fetching the h1-Element in a Variable
var headingText = heading.firstChild.nodeValue; // saving the text alone separately,
// which is "Shopping-List"
var totalItems = listItems.length; // saving the number of Items
// creating a new Title, by adding an em-Element to the previously saved "headingText"
var newHeading = headingText + '<em id="subTitle">' + totalItems + '</em>';
console.log(newHeading.textContent); // this retuns "undefined"
heading.textContent = newHeading;
console.log(heading.textContent); // this returns the Title-Text + Item-Sum + parent-em-
// node. I thought .textContent ***hides the html***?
最佳答案
为了达到预期的结果,使用下面的选项,因为 newHeading 是一个字符串
newHeading.substring(
newHeading.indexOf(">") + 1,
newHeading.indexOf("</")
)
codepen 供引用 - https://codepen.io/nagasai/pen/VGoJmE
关于javascript - 无法隐藏 <em>-Element,它在 Javascript 中作为 String 添加; textContent 不隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52524155/