Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,

$("#myDiv").html(result);

converts "result" (which is the html code) into normal text and display it in myDiv.

Now, my question is, is there a way I can simply convert the html and put it into a variable?

for example:

var temp;
temp = html(result);

something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.

Edit:

Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?

like image 408
eastboundr Avatar asked Nov 28 '11 17:11

eastboundr


People also ask

How do I get just the text from HTML in jQuery?

jQuery html() Method Tip: To set or return only the text content of the selected elements, use the text() method.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


2 Answers

Here is no-jQuery solution:

function htmlToText(html) {
    var temp = document.createElement('div');
    temp.innerHTML = html;
    return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}

Works great in IE ≥9.

like image 125
Finesse Avatar answered Sep 19 '22 21:09

Finesse


No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.

You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:

var d = $('<div>').html(result);

Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:

var d = $(result);

Now you have a jQuery object that contains the elements from the parsed HTML code.

like image 42
Guffa Avatar answered Sep 22 '22 21:09

Guffa