- Create string from HTMLDivElement
- 8 Answers 8
- 3 ways to convert HTML text to plain text
- 1) Using .replace(/<[^>]*>/g, ‘’)
- 2) Create a temporary DOM element and retrieve the text
- 3) html-to-text npm package
- Installation
- Usage
- How to convert the html object to string type
- How to Convert an HTML Node to a String in JavaScript
- Using Vanilla JS getElement Methods VS JQuery
- Examples by Node Selection Methods:
- Using innerHTML() vs outerHTML()
- Extracting HTML Code from a DOM Node – getElementById() Example
- Extracting HTML Code from a DOM Node – getElementsByClassName() Example
- Extracting HTML Code from a DOM Node – getElementsByName() Example
- Extracting HTML Code from a DOM Node – getElementsByTagName() Example
- Read More From Actual Wizard
- Primary Sidebar
- More posts from this section
- Javascript convert html string to string
- TL;DR
Create string from HTMLDivElement
What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:
var day = document.createElement("div"); day.className = "day"; day.textContent = "Random Text";
8 Answers 8
Variant on Gump’s wrapper, since his implementation lifts the target node out of the document.
function nodeToString ( node ) < var tmpNode = document.createElement( "div" ); tmpNode.appendChild( node.cloneNode( true ) ); var str = tmpNode.innerHTML; tmpNode = node = null; // prevent memory leaks in IE return str; >
To print the resulting string on screen (re: escaped)
var escapedStr = nodeToString( node ).replace( "" , ">"); outputNode.innerHTML += escapedStr;
Note, attributes like «class» , «id» , etc being stringified properly is questionable.
Simple yet effective, just what i was looking for. Its a pity the outerHTML method is not supported by Firefox. Thanks
You can use this function (taken from pure.js)
A few years have passed since the last answers. So here is an easier approach:
I found out that .outerHTML is supported by all major browsers now (see caniuse). You can use it to get the HTML of an JS element with ease:
// Create a sample HTMLDivElement var Day = document.createElement("div"); Day.className = "day"; Day.textContent = "Random Text"; // Log the element's HTML to the console console.log(Day.outerHTML)
You can wrap that element into another element and use innerHTML on it:
var wrapper = document.createElement("div"); wrapper.appendChild(day); var str = wrapper.innerHTML;
You need to create text node to add text for your created element like this:
var day = document.createElement("div"); day.className = "day"; // create text node var txt = document.createTextNode('Random Text'); // add text to div now day.appendChild(txt); // append to body document.body.appendChild(day);
3 ways to convert HTML text to plain text
I was working with a rich text editor the other day and needed to strip the HTML tags from the string and store it in the database. And here are the few ways I learned that could come in handy to anyone who is trying to do the same.
What we are trying to do is remove the tags from the string and make the string printable as plain text. Let’s dive in and see how it works.
1) Using .replace(/<[^>]*>/g, ‘’)
This method is a simple and efficient way to remove the tags from the text. This method uses the string method .replace(old value,new value) which replaces the HTML tag values with the empty string. The /g is used for it to happen globally (every value found in the string is replaced with the specified if the /g is used).
The drawback of this method is that we can’t remove some HTML entities. It still works well though.
var myHTML= "Jimbo.
\nThat's what she said
"; var strippedHtml = myHTML.replace(/[^>]+>/g, ''); // Jimbo. // That's what she said console.log(stripedHtml);
2) Create a temporary DOM element and retrieve the text
This is the most efficient way of doing the task. Create a dummy element and assign it to a variable. We can extract later using the element objects. Assign the HTML text to innerHTML of the dummy element and we will get the plain text from the text element objects.
function convertToPlain(html) // Create a new div element var tempDivElement = document.createElement("div"); // Set the HTML content with the given value tempDivElement.innerHTML = html; // Retrieve the text property of the element return tempDivElement.textContent || tempDivElement.innerText || ""; > var htmlString= "Bears Beets Battlestar Galactica
\nQuote by Dwight Schrute
"; console.log(convertToPlain(htmlString)); // Expected Result: // Bears Beets Battlestar Galactica // Quote by Dwight Schrute
3) html-to-text npm package
This is the package I discovered recently. This is the converter that parses HTML and returns beautiful text. It comes with many options to convert it to plain text like wordwrap , tags , whitespaceCharacters , formattersetc .
Package.json is needed to use the package. We need to install the package first and then use it in our file.
You can find the official doc of the package here.
Installation
Usage
const htmlToText > = require('html-to-text'); const text = htmlToText('Nope Its not Ashton Kutcher. It is Kevin Malone. Equally Smart and equally handsome
', wordwrap: 130 >); console.log(text); // expected result: // Nope Its not Ashton Kutcher. It is Kevin Malone. // Equally Smart and equally handsome
How to convert the html object to string type
In this article, you will take a look at how to convert the html object to string type.
Sometimes, when we try to display an element from another elements using JavaScript, we see the [object HTMLDivElement] html object.
Suppose, we have a element, inside it we have a and a
elements.
div id="my-div"> h4>This is a heading tag./h4> p>This is a paragraph./p> /div>
We want to display the above element to a new element when a button is clicked using JavaScript.
button onclick="myFunction()">Click Me/button> div id="output"> /div>
div id="my-div"> h4>This is a heading tag./h4> p>This is a paragraph./p> /div> div id="output"> /div> button onclick="myFunction()">Click Me/button> script> const myInput = document.querySelector('#my-div') const myOutput = document.querySelector('#output') function myFunction() myOutput.innerHTML = myInput > /script>
In the above example, we seen the problem. Here we should use the innerHTML Or innerText property to get the value of the element.
div id="my-div"> h4>This is a heading tag./h4> p>This is a paragraph./p> /div> div id="output"> /div> button onclick="myFunction()">Click Me/button> script> const myInput = document.querySelector('#my-div') const myOutput = document.querySelector('#output') function myFunction()< myOutput.innerHTML = myInput.innerHTML > /script>
How to Convert an HTML Node to a String in JavaScript
For various reasons, you may want to get the HTML code of a specific element in an HTML document.
This is relatively easy to do, with the main problem being that you will need to identify a unique way to select the specific node that you desire.
Using Vanilla JS getElement Methods VS JQuery
Although it is possible to achieve this with JQuery, this task is easy to accomplish using vanilla JavaScript methods, and all of the following examples will use vanilla JavaScript.
The nice thing about each of these examples is that the HTML code will be in a string variable and not an object.
Examples by Node Selection Methods:
getElementById() – This method is likely going to be your best option as long as the element has a unique ID, or is the first element with that unique ID. Unfortunately, this method will not work if you need to specify a DOM node with an ID that is not the first node on the page with that specific ID.
getElementsByClassName() – This method isn’t the best choice as CSS typically targets nodes by their class names. It can work in some situations, and one big difference between getElementById() is that it will return multiple nodes with the same class name.
getElementsByName() – This method is also a good choice as any element in an HTML document can be assigned a unique name value. If there are multiple elements with the same name, you can select a specific element by it’s index value (order value) on the page.
getElementsByTagName() – This method isn’t that great of a choice unless you have no other options. The big issue here is that an HTML document could have many elements with the same tag name, and it could be difficult to find the specific element that you are looking for by it’s tag.
Using innerHTML() vs outerHTML()
In most cases, you will likely want to use the outerHTML method on the node that your code has selected.
OuterHTML includes the tag of the node itself, whereas the innerHTML method does not.
The innerHTML of the someid node is:
The outerHTML of the someid node is:
Extracting HTML Code from a DOM Node – getElementById() Example
Extracting HTML Code from a DOM Node – getElementsByClassName() Example
- Example Element One
- Example Element Two
- Example Element Three
- Example Element Four
- Example Element Five
- Example Element Six
Extracting HTML Code from a DOM Node – getElementsByName() Example
- Example Element One
- Example Element Two
- Example Element Three
- Example Element Four
- Example Element Five
- Example Element Six
Extracting HTML Code from a DOM Node – getElementsByTagName() Example
- Example Element One
- Example Element Two
- Example Element Three
- Example Element Four
- Example Element Five
- Example Element Six
Read More From Actual Wizard
An email address has four parts; the recipient name, the @ symbol, the domain name, and the top-level domain. …
There are a number of different ways to get the last element of an array in JavaScript. Below we will explore …
How to use document.write() in JavaScript The document.write() function is commonly used when testing simple …
Opening a new browser window in a new tab can be done easily in JavaScript. Modern web browsers provide a …
Primary Sidebar
More posts from this section
Copyright © 2023 ActualWizard.com
Javascript convert html string to string
April 26, 2021 — 2 min read
To convert an HTML string into real HTML or DOM, you can use the DOMParser Web API using JavaScript. The DOMParser helps us to parse HTML or XML string into real Document or DOM nodes.
TL;DR
// html string const htmlStr = "Hello World!
"; // make a new parser const parser = new DOMParser(); // convert html string into DOM const document = parser.parseFromString(htmlStr, "text/html");
For example, let’s say you have a HTML string of h1 tag with the text of Hello World! like this,
// html string const htmlStr = "Hello World!
";
Now, to convert this string into a real HTML tag we can use the DOMParser web API.
So first, we have to make a parser using the new keyword like this,
// html string const htmlStr = "Hello World!
"; // make a new parser const parser = new DOMParser();
After that, we can use the parseFromString() method in the parser object and pass:
- the raw HTML string as the first argument
- and the mime type or the type of the document contained in the string as the second argument. In our case, the mime-type value is text/html .
There are other mime types we can use such as:
So it will look like this,
// html string const htmlStr = "Hello World!
"; // make a new parser const parser = new DOMParser(); // convert html string into DOM const document = parser.parseFromString(htmlStr, "text/html");
Now the HTML string is converted to an HTML DOM node. You can now use the usual methods and properties available on a DOM node such as appendChild() , classList , etc.
See the above code live in JSBin.