famas23
famas23

Reputation: 2280

Html string to jquery object

I have this html text :

<!-- START X::news/news_filters.html.twig -->
<div class="row"></div>
<!-- STOP X::news/news_filters.html.twig -->

And I want to parse it and find the div row, unfortunately console.log($($.parseHTML(html))); return an object with 5 elements:

Object(5)
​
0: <!--  START X…/news_filters.html.twig  -->
​
1: #text "
"
​
2: <div class="row">
​
3: #text "
"
​
4: <!--  STOP X…/news_filters.html.twig  -->
​
length: 5
​
<prototype>: Object { jquery: "3.2.1", constructor: r(), length: 0, … }
4cec809_script_10.js:1:50083

Any idea how i can parse my html text to get a properly jquery object.

Upvotes: 1

Views: 53

Answers (1)

Jamiec
Jamiec

Reputation: 136094

Calling $.parseHTML gives you an array of DOM nodes. You can then pass this to the jQuery constructor to get a jQuery object.

Once you've done that, you can use normal jQuery methods like filter to find the element you're interested in:

var str = '<!-- START X::news/news_filters.html.twig --><div class="row">hello</div><!-- STOP X::news/news_filters.html.twig -->';

var $html = $($.parseHTML(str));
var $div = $html.filter("div.row")
console.log($div.text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 3

Related Questions