I recently had a string with some content from a WYSIWYG editor (What you see is what you get). In there, I needed to find all the href elements. Show But this specific approach can work for many things. My approach consists of using the Using JavaScript to get HTML elements from a stringTo get started, let's first define our
As you can see, we have two links in there. Let's say we want to parse each link to add a We can leverage the
This console.log will return the following object. As you can see, this is a full document. To get all the links, we can use regular queries on this doc const.
Nice, we got our two links. We can loop over these two links and manipulate them. This will be adjusted in our doc variable.
Here we loop over the getElementsByTagName results, and set the target to a blank page. Now, if we would log the current status:
We get the following result. You can see the links now have a target blank. Using the output of a JavaScript DOMParserLet's also take some time to output the
changes to see them in the Let's add two divs to our
First, we have our basic text variable.
Next, we will get the two div elements.
For the original one, we can immediately add the output as-is.
And for the output one, we do our modifications as seen above.
That's it. We now have two divs, one with links that open in the same tab and open in a blank tab. Try it out using the following Codepen. See the Pen JavaScript get HTML elements from a string by Chris Bongers (@rebelchris) on CodePen. Thank you for reading, and let's connect!Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter How do I check if a string contains HTML?test. bind(/(<([^>]+)>)/i); It will basically return true for strings containing a < followed by ANYTHING followed by > .
How do you display HTML tags in JavaScript?JavaScript can "display" data in different ways:. Writing into an HTML element, using innerHTML .. Writing into the HTML output using document.write() .. Writing into an alert box, using window.alert() .. Writing into the browser console, using console.log() .. How do I find tags in HTML?Right-click while on your webpage in Google Chrome. Click 'Inspect' You'll see the HTML code in a box at the side or bottom of your page. Use Ctrl + F to find particular tags or elements.
What is string HTML?A string can be any text inside double or single quotes: let carName1 = "Volvo XC60"; let carName2 = 'Volvo XC60'; String indexes are zero-based: The first character is in position 0, the second in 1, and so on.
|