In JavaScript, you can use the innerText or textContent property to get the text of an HTML element.

// get the text of an element with id "example"
var text = document.getElementById("example").innerText;
//or 
var text = document.getElementById("example").textContent;

Note that innerText is not supported by all browsers, textContent is more widely supported and recommended.

You also can use querySelector or querySelectorAll to select the element with css selector

// get the text of an element with class "example"
var text = document.querySelector(".example").innerText;
//or 
var text = document.querySelector(".example").textContent;
// get the text of all elements with class "example"
var elements = document.querySelectorAll(".example");
for (var i = 0; i < elements.length; i++) {
    var text = elements[i].innerText;
    //or 
    var text = elements[i].textContent;
}

Please note that the above methods only work if the element is present in the DOM when the script is executed.

Also Read:

Categorized in: