简体   繁体   English

替换 class 名称的文本,但在特定 id 内

[英]Replace text of a class name but within a particular id

I have the following html:我有以下 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>

and I'm trying to update the text shown in the class modal-heading-text-after for this particular id heading:我正在尝试更新此特定 id 标题的 class modal-heading-text-after中显示的文本:

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

But it's not working.但它不起作用。 Any ideas?有任何想法吗? My environment setup is strange and I can't see errors.我的环境设置很奇怪,我看不到错误。

Your issue here is that getElementsByClassName returns an array of matches.您的问题是getElementsByClassName返回一个匹配数组。

So when you try and set the text attribute you're actually setting it against the matching set of HTML elements - not a HTML element within that array.因此,当您尝试设置text属性时,实际上是针对匹配的 HTML 元素进行设置 - 而不是该数组中的 HTML 元素。

There may only be 1 element in that set, but it will always return an array, not a single element.该集合中可能只有 1 个元素,但它始终会返回一个数组,而不是单个元素。

If you change the second line to address the [0] index element within that array it should work.如果您更改第二行以解决该数组中的[0]索引元素,它应该可以工作。

The final code for your JS would look like this:您的 JS 的最终代码如下所示:

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

That should then work.那应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM