Suppose I have an HTML string like below:
<div style="margin-top:10px" data-href="/URL" data-Id="1"> Some text here </div>
now what I need to do is get only Text part from the above HTML string, i.e. "Some text here", so how can I get only Text part from HTML string using javascript or jQuery?
Please Note: I have HTML string here, and It is not already in DOM, so I cannot get it HTML element using its class or Id in javascript and get Text.
 Answered by:- manish
                            
                        
                        Answered by:- manish  
                    You can use the following javascript code to extract only Text part from HTML string
function GetHtml(html){
    // Create a new div element
    var temporaryDivElement = document.createElement("div");
    // Set the HTML content with the providen
    temporaryDivElement.innerHTML = html;
    // Retrieve the text property of the element (cross-browser support)
    return temporaryDivElement.textContent || temporaryDivElement.innerText || "";
}In the above method, we are creating a temporary div and then appending our given HTML string to it,after that we will Get inner text of html only.
So, you can use it like
function GetHtml(html){
    // Create a new div element
    var temporaryDivElement = document.createElement("div");
    // Set the HTML content with the providen
    temporaryDivElement.innerHTML = html;
    // Retrieve the text property of the element (cross-browser support)
    return temporaryDivElement.textContent || temporaryDivElement.innerText || "";
}
var htmlStr ='<div style="margin-top:10px" data-href="/URL" data-Id="1">Some text here</div>';
//Output : Some text here
console.log(GetHtml(htmlStr));Using Jquery, we can do it in simpler way
var htmlString= "<div>\n <h1>Hello World</h1>\n <p>This is the text that we should get.</p>\n <p>Our Code World © 2017</p>\n </div>";
var stripedHtml = $("<div>").html(htmlString).text();
// Hello World
// This is the text that we should get.
// Our Code World © 2017
console.log(stripedHtml);Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly