开发者

Unable to change anchor.text

开发者 https://www.devze.com 2023-03-10 15:06 出处:网络
I\'m trying to change the text in the anchors as follows: for (var i = 0; i < anchors.length; i++) {

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:

  1. MDC: https://developer.mozilla.org/En/DOM/Node.textContent
  2. MSDN: http://msdn.microsoft.com/en-us/library/ms533899%28v=VS.85%29.aspx
  3. 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 += "+";
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消