Click here to Skip to main content
15,884,064 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<pre lang="Javascript">
 function chngetxt(){
 var items = document.getElementsByClassName('items');
      console.log(items);
       items.textContent="goodbye";}

<pre lang="HTML">
 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link type="text/CSS" href="C:/Users/ITDEPARTEMENT/Desktop/practice/DOM.css" rel="stylesheet"/>
    <title>the page</title>
    
  </head>
  <body >
    
    <h1 class="items">the items</h1>
    <ul >
      <li >item1</li>
      <li>item2</li>
      <li>item3</li>
      <li>item4</li>
      <li>item5</li>
    </ul>
    <form>
      <button onclick="chngetxt();">clickme to change the text</button>
    </form>
    <script  src="DOM.js">
      
    </script>
   
  </body>
</html>


What I have tried:

i have tried to change the position of the script tag but it is not changing m text .
o would suspect that it may be the browser but am not sure .anyway am using chrome.
Posted
Updated 15-Sep-21 3:50am
Comments
Nathan Minier 21-Jul-21 14:21pm    
You're trying to apply a single object interaction to an array. No, it's not gonna work. Here's the documentation for the method you're using:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

So, unless you want to use a single-element selector (such as getElementById) then you should iterate the result to apply your changes. Like so:

function chngetxt(){
var items = document.getElementsByClassName('items');
for(let i = 0; i < items.length; i++){
items[i].textContent="goodbye";
}
}
SeeSharp2 22-Jul-21 9:06am    
You should post as solution, but I don't think textContent is correct. Should be innerText.

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
Nathan Minier 22-Jul-21 9:13am    
According to MDN innerContent is the same thing, but doesn't go through the HTML parser so has less overhead. I've never used it before, but that doesn't mean I'm not willing to give it a shot.
SeeSharp2 22-Jul-21 9:40am    
textContent (not innerContent) was new to me too but the documentation says it also gets child elements. I doubt they want that, even though there are none.
munaziri BNM 22-Jul-21 4:39am    
Nathan thank you very much

1 solution

use
innerText
instead of
textContent
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900