Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将文本附加到现有的span标记_Javascript - Fatal编程技术网

Javascript 将文本附加到现有的span标记

Javascript 将文本附加到现有的span标记,javascript,Javascript,我有下面的HTML <div class="card-text" data-test-info-type="price"> <div class="price-section price-section--withoutTax "> <span data-product-price-without-tax="" class="price price--withoutTax">$20.00</span> </div>

我有下面的HTML

<div class="card-text" data-test-info-type="price">
  <div class="price-section price-section--withoutTax ">
      <span data-product-price-without-tax="" class="price price--withoutTax">$20.00</span>
  </div>
</div>
但仍然是20美元

然后我试着

document.getElementsByClassName('price price--withoutTax').innerHTML = "hello";
同样的结果还是20美元


有人能告诉我如何在span标记中添加额外的文本吗?

问题是
文档。getElementsByClassName
返回一个HTML集合,或一组“数组”结构中的元素。这意味着:

var span = document.getElementsByClassName("price price--withoutTax");
span.innerText = ...;
将不起作用,因为
span
不是一个元素,而是一个列表。即使有一个元素具有类名,它也会返回一个只包含一个元素的列表。如果只需要第一个元素,或只使用第一个元素,请执行以下操作:

var span = document.getElementsByClassName("price price--withoutTax")[0];

请注意
[0]
。这将访问“数组”的第一个元素,如
document.getElementByClassName的返回值,为您提供具有给定类名的第一个元素。如果要获取多个元素的值,可以在其上循环并对每个元素执行任何操作。

getElementsByClassName
返回一个列表。您必须设置索引(例如,[0])。创建文本节点只是为了检索其文本内容有什么意义?为什么不直接使用
“Prices…”
字符串?此外,一旦您解决了返回列表的问题,您将覆盖范围的现有内容,而不是添加到内容中。@CodeRatchet,我认为除了上述添加到您的问题之外,还有一个正确的解决方案,请检查此和工作演示
var span = document.getElementsByClassName("price price--withoutTax")[0];