javascript - Uncaught TypeError: getElementsByName is not a function - Stack Overflow

I have a bunch of elements on a page that are formatted like below:<div class="longdesc"&g

I have a bunch of elements on a page that are formatted like below:

<div class="longdesc">
 <pre style="...">
   //stuff here
 </pre>
</div>
<div class="longdesc">
 <pre style="...">
   //stuff here
 </pre>
</div>

I'm trying to replace some of the content inside the <pre> tag but I'm having trouble.

(function () {    
    var nodes = document.getElementsByClassName("longdesc");
    for (var n=0; n<nodes.length; n++) {
        var node = nodes[n].getElementsByName("pre");
        node[0].textContent = node[0].textContent.replace("<", "&lt;");
        //other code
    }
})();

VM5185:4 Uncaught TypeError: nodes[n].getElementsByName is not a function

I only need the first pre in each longdesc. How can I do this?

I have a bunch of elements on a page that are formatted like below:

<div class="longdesc">
 <pre style="...">
   //stuff here
 </pre>
</div>
<div class="longdesc">
 <pre style="...">
   //stuff here
 </pre>
</div>

I'm trying to replace some of the content inside the <pre> tag but I'm having trouble.

(function () {    
    var nodes = document.getElementsByClassName("longdesc");
    for (var n=0; n<nodes.length; n++) {
        var node = nodes[n].getElementsByName("pre");
        node[0].textContent = node[0].textContent.replace("<", "&lt;");
        //other code
    }
})();

VM5185:4 Uncaught TypeError: nodes[n].getElementsByName is not a function

I only need the first pre in each longdesc. How can I do this?

Share Improve this question asked Mar 29, 2016 at 18:56 user736893user736893 3
  • 1 You need .getElementsByTagName("pre"); – The Process Commented Mar 29, 2016 at 18:57
  • please post as answer... – user736893 Commented Mar 29, 2016 at 18:59
  • See the reason why stackoverflow./a/70055419/560287 – John Magnolia Commented Aug 17, 2022 at 6:26
Add a ment  | 

2 Answers 2

Reset to default 2

try this:

(function () {    
    var nodes = document.getElementsByClassName("longdesc");
    for (var n=0; n<nodes.length; n++) {
        var node = nodes[n].getElementsByTagName("pre");
        node[0].textContent = node[0].textContent.replace("<", "&lt;");
        //other code
    }
})();

Try using getElementsByTagName() instead.

http://www.w3schools./jsref/met_element_getelementsbytagname.asp

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744279508a4566499.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信