Find element in a string of HTML using jQuery

In JavaScript/jQuery we have a string of HTML that is the value of a JavaScript varible like below:
var stringHTML = '<h2>Heading</h2><div class="content">
<div>This is the content section first</div>
<div>This is the content section second</div></div>
<span class="caption">This is caption</span>';

Now we need the span element from the HTML string. Using JavaScript/jQuery we can very easily do that. The following code should simply give us the span element from the HTML string. 

var captionElm = $(stringHTML).find('.caption');
 console.log(captionElm);

But the above code can't find the span element from the HTML string.

Why find method could not get the span?

jQuery find method looks for the span element inside the HTML string in whole hierachy except root elements. In the HTML string above the span lies in the root element so jQuery find method could not find the span. 

How to solve the issue?

To solve this issue it is always a good idea to wrap the HTML string in an element. This will grurantee that all the elements inside the HTML string will be searched by the find method. See the working code: 


var captionElm = $('<div>').append(stringHTML).find('.caption');
 console.log(captionElm);

Comments