使用JavaScript替换DIV中的文本内容

时间:2017-03-30 13:15:30

标签: javascript jquery html dom javascript-events

我想只更改h1标签内的文本内容。这是我的代码:



<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">
	
	  <span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>
	
  </span>

</h1>
&#13;
&#13;
&#13;

我已尝试过此代码:

&#13;
&#13;
document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";
&#13;
&#13;
&#13; 但它不起作用,结果如下:

&#13;
&#13;
<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">text changed</span>

</h1>
&#13;
&#13;
&#13;

任何帮助将不胜感激

4 个答案:

答案 0 :(得分:3)

您必须使用querySelector()方法才能更改超链接的文本内容。

document.querySelector("#pageTitle a").innerHTML = "text changed";
<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">
	
  <span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>
  </span>
</h1>

答案 1 :(得分:2)

你正在做的是改变&#34; DeltaPlaceHolderPageTitleInTitleArea&#34;因此,您可以替换:

的innerHTML
<span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>

使用:

text changed

你想改变的是标题的文字,我是对的吗?为此:

非常基本的JS:

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").children[0].children[0].children[0].innerHTML = "text changed";

更先进一点:

document.querySelector("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").innerHTML = "text changed";

或者使用jQuery:

$("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").text("text changed");

答案 2 :(得分:1)

你可以尝试一下。

function changeContent(){

var element = document.getElementById('DeltaPlaceHolderPageTitleInTitleArea');
element.children[0].innerHTML = "whatever";
}
<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

    <a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>

	</span>
  
  <button name="change content" onClick="changeContent()">change content</button>

</h1>

答案 3 :(得分:0)

您指向h1标记的id,而不是包含要更改的文本的anchor()标记。这个我不确定是否允许您将文本准确插入到您想要的位置。使用查询选择器或任何其他方法选择包装文本的标签,你肯定会做什么改变。如果你不介意,jquery选择器将更容易地完成工作

您可以尝试import os, pandas filename = "VeryLong.csv" lines_number = sum(1 for line in open(filename)) lines_in_chunk = 500 # I don't know what size is better counter = 0 completed = 0 reader = pandas.read_csv(filename, chunksize=lines_in_chunk) for chunk in reader: # < ... reading the chunk somehow... > # showing progress: counter += lines_in_chunk new_completed = int(round(float(counter)/lines_number * 100)) if (new_completed > completed): completed = new_completed print "Completed", completed, "%"

之类的内容