![](/img/trans.png)
[英]How do I change the color of the header with JavaScript (I am using innerHTML) without changing the text as well?
[英]How do I replace text without using innerHTML?
假设我有一个看起来像这样的节点
<a>
<span class="glyphicons glyphicons-collapse"></span>Collapse All
</a>
我想切换到这个
<a>
<span class="glyphicons glyphicons-expand"></span>Expand All
</a>
如果我使用innerHTML
或innerText
或textContent
它将替换文本。 我对解决方案的第一遍是
function toggleLastTextNode(element, textWhenTrue, textWhenFalse, value) {
element.removeChild(obj.childNodes[1]);
element.insertAdjacentHTML("beforeend", value ? textWhenTrue: textWhenFalse);
}
据我所知,文本始终在obj.childNodes[1]
因此我将其删除并替换。 函数调用将是这样的
toggleLastTextNode(element,"Expand","Collapse",true)
使用当前的HTML,还有更好的方法吗? 如果可以的话,我想避免使用innerHTML。
怎么样
document.getElementById('elementid').firstChild.nodeValue = new_text;
innerHTML有副作用(例如断开现有的DOM节点并重新呈现可能很重的内容)。
如今,当我面对这种功能时,我总是尝试着去看语义学,去掉所有不满足的东西。 在这种情况下,您可以将文本保留在CSS中,因为它只是UX / UI而不是内容的一部分(例如,屏幕阅读器不应“读取”此内容,例如Google搜索机器人,它也不能做任何事情)对该内容有用)。 在您的情况下,不更改HTML(也可能会缩短HTML),我得出了这样的解决方案:
HTML(与您的HTML几乎相同,添加了href
属性):
<a href="#">
<span class="glyphicons glyphicons-collapse"></span>
</a>
CSS:
.glyphicons-collapse::after{content: 'Collapse All'}
.glyphicons-expand::after{content: 'Expand All'}
JS(jquery):
$('a').on('click','.glyphicons-collapse',function(e){
e.preventDefault();
$(this).removeClass('glyphicons-collapse');
$(this).addClass('glyphicons-expand');
});
$('a').on('click','.glyphicons-expand',function(e){
e.preventDefault();
$(this).removeClass('glyphicons-expand');
$(this).addClass('glyphicons-collapse');
});
用id定义你的html内容
<a id="glyphicons">
<span class="glyphicons glyphicons-collapse"></span>Collapse All
</a>
然后toggleExpandCollapse()
var toggleExpandCollapse = function () {
var oElements = document.getElementById('glyphicons').childNodes;
if (oElements[1].className === "glyphicons glyphicons-collapse") {
oElements.childNodes[2].nodeValue = "Expand All";
oElements[1].className = "glyphicons glyphicons-expand"
} else {
oElements.childNodes[2].nodeValue = "Collapse All";
oElements[1].className = "glyphicons glyphicons-collapse"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.