Answers for "how to grab text content from javascript"

1

javascript get text from div

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

<div id="test">
  Some <span class="foo">sample</span> text.
</div>
You'll get the following result:

var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."

textContent = node.textContent;
// textContent = "Some sample text."
Posted by: Guest on March-04-2021
0

get text from html string javascript

<input id="input" />
<div id="div" contenteditable="true">Text in DIV</div>
<p id="p" contenteditable="true">Text in paragraph</p>
<script type="text/javascript">
  // function to get text from HTML element
  function getText(id) {
    // if element is input then return the value
    if (document.getElementById(id).nodeName === "INPUT") {
      return document.getElementById(id).value;
    }
    // otherwise return the textContent
    return document.getElementById(id).textContent;
  }
  // print the current values
  console.log(getText("div"));
  console.log(getText("p"));
</script>
Posted by: Guest on July-16-2021

Code answers related to "how to grab text content from javascript"

Browse Popular Code Answers by Language