I'm trying to change the text in the anchors as follows:
for (var i = 0; i < anchors.length; i++) {
...
anchors[i].text = anchors[i].text + "+";
}
I tried alternative methods like concat
and append
but 开发者_Go百科nothing works.
anchors[i].innerHTML
helped but the code is called on DOMContentLoaded and I want to add only "+" string, instead of it I'm adding unpredictable sequence of "+"* e.g. "++++++++"
thank you for help
Simply put, HTMLElement.innerHTML
is for HTML strings. In your case, you're looking for Node.textContent
and the non-standard Node.innerText
since you're just replacing text.
var anchors = document.links;
for(var i=0;i<anchors.length;i++)
{
var anchor = anchors[i];
if(anchor.textContent)
{
//W3C DOM
anchor.textContent += "+";
}else if(anchor.innerText)
{
//Microsoft DOM
anchor.innerText += "+";
}
}
When dealing with older browsers, you can use a snippet like the one bobince provided here (do note that it will clear the childNodes clean and replace them with a text node): 'innerText' works in IE, but not in Firefox
Reference:
- MDC: https://developer.mozilla.org/En/DOM/Node.textContent
- MSDN: http://msdn.microsoft.com/en-us/library/ms533899%28v=VS.85%29.aspx
- W3C DOM Level 3: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent
JavaScript DOM does not have .text. It has .innerHTML
If you mean the link text:
var anchors = document.getElementsByTagName("A");
for (var i = 0; i < anchors.length; i++) {
anchors[i].innerHTML += "+";
}
精彩评论