Javascript dom parse html

О скромном DOMParser замолвите слово

Данная статья посвящена одному из объектов Web API Interfaces, а именно — DOMParser.
Поиск на Хабре выдаёт 7 статей, где он упоминается лишь вскользь. Мне кажется, это требует исправления.

Коротко и по делу:

  • DOMParser предназначен для парсинга «сырой» строки HTML, XML, SVG в объект. Обратный парсинг также не составляет труда;
  • Для парсинга DOMParser располагает методом «parseFromString». Результатом работы данного метода является объект DOM, а если точнее – это либо объект HTMLDocument (в случае HTML), либо объект Document (в случае XML), либо SVGDocument (в случае SVG);
  • здесь написано что данный объект относится к экспериментальной части API. А вот здесь сказано какими браузерами и их версиями он поддерживается (если коротко – последние версии большой браузерной пятерки поддерживают);
  • далее будет идти речь только в контексте парсинга HTML
  • Наверное, вас интересует вопрос, а все ли сущности HTML попадают в итоговый объект при парсинге? Ответ — все, кроме тега . Согласитесь, это мелочь, в мире нет ничего идеального;
  • С полученным объектом можно «играться» как с любым другим DOM-объектом, легко можно внедриться в него с помощью того же jQuery, заменить там что-нибудь ненужное на что-нибудь нужное. После этого можно выполнить обратный парсинг (из объекта в строку). Тут не забываем про тег !doctype, он исчезнет (см. выше);
  • Что с «обломами»? Есть одна проблемка — если парсинг заканчивается неудачей то исключение не бросается, а возвращается «кривой» объект HTMLDocument. Данный баг имеет красивый номер 45566.

var parser = new DOMParser(); //создаем объект DOMParser //парсим var doc = parser.parseFromString(html_text, «text/html»); //html_text — это текст который мы хотим распарсить. Второй аргумент, это MIME-тип, для XML он должен быть равен «application/xml», для SVG — «image/svg+xml») var jq = $(‘a’, doc); //получаем jQuery-коллекцию всех тегов «a» jq.each(function()< //заменяем в каждом и теге значение атрибута "href" $(this).attr("href", "new.html"); >); //и наконец делаем обратный парсинг console.log(«result tm-article-body__tags»>

Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

Читайте также:  Packet sniffing in python

О песочнице

Это «Песочница» — раздел, в который попадают дебютные публикации пользователей, желающих стать полноправными участниками сообщества.

Если у вас есть приглашение, отправьте его автору понравившейся публикации — тогда её смогут прочитать и обсудить все остальные пользователи Хабра.

Чтобы исключить предвзятость при оценке, все публикации анонимны, псевдонимы показываются случайным образом.

О модерации

  • рекламные и PR-публикации
  • вопросы и просьбы (для них есть Хабр Q&A);
  • вакансии (используйте Хабр Карьеру)
  • статьи, ранее опубликованные на других сайтах;
  • статьи без правильно расставленных знаков препинания, со смайликами, с обилием восклицательных знаков, неоправданным выделением слов и предложений и другим неуместным форматированием текста;
  • жалобы на компании и предоставляемые услуги;
  • низкокачественные переводы;
  • куски программного кода без пояснений;
  • односложные статьи;
  • статьи, слабо относящиеся к или не относящиеся к ней вовсе.

Источник

Parse an HTML String With JS – JavaScript

While maintaining the records in JavaScript, there can be a requirement to maintain multiple entries for utilizing them in the future. For instance, appending various vital HTML functionalities in JavaScript to get rid of their effects for a certain time. In such situations, parsing an HTML string with JS is of great aid in reducing the overall code complexity.

This tutorial will demonstrate the strategies to parse an HTML string with JavaScript.

How to Parse an HTML String Using JavaScript?

To parse an HTML string with JavaScript, apply the following strategies:

Method 1: Parse an HTML String in JavaScript Using the createElement() Method and innerHTML Property

The “createElement()” method is used to generate a node for an HTML element dynamically, and the “innerHTML” property gives the HTML content of an element. These approaches can be applied to create an element in JavaScript code and append an HTML string to it.

In this syntax, “elementName” refers to the HTML element that needs to be created.

Example

Let’s go through the below-stated demonstration:

let myPara = document. createElement ( ‘p’ ) ;

myPara. innerHTML = «

This is Linuxhint

By JavaScript

» ;

  • Firstly, create an HTML element named “p” using the “createElement()” method.
  • In the next step, append the stated HTML element using the “innerHTML” property.
  • Lastly, display the created element accumulating the parsed HTML string on the console.

From the given output, it can be seen that the “ ” element is successfully created, and the parsed HTML strings are displayed.

Method 2: Parse an HTML String in JavaScript Using the DOMparser() Constructor and parseFromString() Method

The “DOMparser()” constructor creates the DOM parser object, and the “parseFromString()” method is used to parse the containing string to the HTML or XML document. These approaches can be applied to parse an HTML string by specifying the document type.

  • string” corresponds to the element that needs to be parsed in the document.
  • mimeType” indicates the document type that invokes the parser type.
Читайте также:  Font in html css and javascript

Example

Let’s go through the below-stated code lines:

let myElement = myDoc. parseFromString ( «

This is Linuxhint

» , ‘text/html’ ) ;

In the above code snippet:

  • Firstly, create a new DOM parser object using the “new” keyword and the “DOMparser()” constructor, respectively.
  • In the next step, associate the created object with the “parseFromString()” method to parse the stated string value.
  • The “text/html” in the method’s parameter specifies that the parsed string is an HTML document.
  • Lastly, display the parsed HTML string on the console.

In the above output, it is evident that the new DOM parser is successfully constructed.

Conclusion

To parse an HTML string with JavaScript, use the “createElement()” method and “innerHTML” property or the “DOMparser()” constructor and “parseFromString()” method. The former approaches can be used to create an HTML element in js code and parse a particular HTML string. The latter approach can be applied to create a new DOM parser object and parse an HTML string by specifying the document type. This write-up discussed the strategies to parse an HTML string with JS.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Javascript dom parse html

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.

Читайте также:  Сумка dolce gabbana кожа питона

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.

Источник

Using DOMParser to Parse HTML Strings

Using DOMParser to Parse HTML Strings

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

I was playing with the WP Rest API plugin to access content from a WordPress blog into an Ionic 2 app. The WP Rest API returns an HTML string for the content of posts, which can make it hard to deal with. Fortunately though, the DOMParser Web API makes it easy to parse html strings into a fully formed DOM. First you instantiate a new DOMParser instance and pass it your HTML string using parseFromString() . For this example, let’s say that we stored the HTML string in a variable called htmlContent:

let parser = new DOMParser(); let parsedHtml = parser.parseFromString(htmlContent, 'text/html'); 
// The src of the first image: let firstImg = parsedHtml.images[0].src; // The li elements of the second ul element: let liElements = parsedHtml.getElementsByTagName("ul")[1].children; 

Taking the second example with li elements, let’s go a bit further and populate an array with the inner HTML of each element:

let rawLiElements = parsedHtml.getElementsByTagName("ul")[1].children; let liElements = []; 

👉 DOMParser is still experimental, so its implementation is subject to change and support can be limited.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью