javascript - 无法隐藏 <em>-Element,它在 Javascript 中作为 String 添加; textContent 不隐藏

标签 javascript html css

问题:我有一个包含元素的列表,我想将所有列表元素的总和添加到 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/

相关文章:

javascript - 如何将运动物理函数缩放到每秒帧数(在游戏引擎中)?

javascript - Meteor 移动 Canvas 不适合屏幕

javascript - 如何正确地将鼠标坐标传递给WebGL?

javascript - 选中其他复选框时取消选中复选框

html - <span>/<div> 是 css 的简写 - 这是合法的吗?

css - Galaxy Galaxy fold 的媒体查询

JavascriptencodeURIComponent和Java解码问题

javascript - 将鼠标悬停在图像上时如何使图像变宽,而其他图像变窄?

html - 缩略图画廊高度问题

html - 使用 CSS,如何将 DIV 移动到中心位置的左侧?