【问题标题】:Replace text of a class name but within a particular id替换类名的文本,但在特定的 id 内
【发布时间】:2022-08-19 16:15:58
【问题描述】:

我有以下html:

<h2 id=\"program-selector-modal_heading\">
  <span class=\"modal-heading-before-text\"></span>
  <span>Start your application to </span>
  <span class=\"modal-heading-after-text\"></span>
</h2>

我正在尝试为这个特定的 id 标题更新 modal-heading-text-after 类中显示的文本:

const programSelectorModalHeadingOuter = document.getElementById(\"program-selector-modal_heading\");
programSelectorModalHeadingOuter.getElementsByClassName(\"modal-heading-after-text\").innerHTML = \"test\";

但它不起作用。有任何想法吗?我的环境设置很奇怪,我看不到错误。

  • 尝试使用 document.querySelector document.querySelector(\'#program-selector-modal_heading .modal-heading-before-text\').innerHTML = \"test\"

标签: javascript


【解决方案1】:

您的问题是 getElementsByClassName 返回一个匹配数组。

因此,当您尝试设置 text 属性时,您实际上是在针对匹配进行设置HTML 元素 - 不是该数组中的 HTML 元素。

该集合中可能只有 1 个元素,但它始终会返回一个数组,而不是单个元素。

如果您更改第二行以解决该数组中的[0] 索引元素,它应该可以工作。

您的 JS 的最终代码如下所示:

const programSelectorModalHeadingOuter = document.getElementById("program-selector-modal_heading");
programSelectorModalHeadingOuter.getElementsByClassName("modal-heading-after-text")[0].innerHTML = "test";

那应该可以工作。

【讨论】:

    猜你喜欢
    • 2022-10-04
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多