The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
JavaScript code that you can use to display the word count of a text in a div element
By Guest on 9th December 2022 09:20:20 PM | Syntax: JAVASCRIPT | Views: 135



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. Here is a sample JavaScript code that you can use to display the word count of a text in a div element:
  2.  
  3. // Get the textbox element
  4. var textbox = document.getElementById("textbox");
  5.  
  6. // Get the word count of the text in the textbox
  7. var wordCount = textbox.value.split(" ").length;
  8.  
  9. // Get the div element where the word count will be displayed
  10. var div = document.getElementById("word-count");
  11.  
  12. // Set the div's innerHTML to the word count
  13. div.innerHTML = "Word Count: " + wordCount;
  14.  
  15.  
  16. In this code, the textbox variable is used to reference the textbox element where the text is entered. Then, the split() method is used to split the text in the textbox by the space character, and the length property is used to get the number of words in the text.
  17.  
  18. Next, the div variable is used to reference the div element where the word count will be displayed. Finally, the innerHTML property of the div element is set to the word count, which displays the word count on the page.
  19.  
  20.  
  21.  
  22. Here is a sample HTML code that you can use to create a textbox and a div element to display the word count:
  23.  
  24.  
  25. <!-- Textbox where the text will be entered -->
  26. <input type="text" id="textbox" placeholder="Enter your text here">
  27.  
  28. <!-- Div element where the word count will be displayed -->
  29. <div id="wordcount"></div>
  30.  
  31.  
  32. In this code, the textbox element is created using the input element with a type attribute of text, and it has an id attribute of textbox so that it can be referenced in the JavaScript code. The div element where the word count will be displayed is created with an id attribute of wordcount, so that it can be referenced in the JavaScript code.
  33.  
  34. You can customize this HTML code to suit your specific needs, such as changing the placeholder text in the textbox, or using a different element to display the word count. You can then use the JavaScript code provided in the previous answer to display the word count in the div element.










  • Recent Pastes