HockChai Lim HockChai Lim - 2 months ago 7
jQuery Question

Jquery find failed to find element without wrapping it with a parent element

jquery seems to not able to find an element without it being wrapped around a parent element.

var data = '<div id="target"> This is what I have </div>';
var result = $(data).find("#target").text();
alert("Without targetParent =>" + result); //Get empty result

data = '<div id="targetParent"><div id="target"> This is what I have </div></div>';
result = $(data).find("#target").text();
alert("With targetParent =>" + result); // Get the "target" element


https://jsfiddle.net/z5roxurq/

Wonder why so.

Answer

The find() method search for descendant element within the selector. To filter element within the selected elements use filter() method.

var result = $(data).filter("#target").text();

var data = '<div id="target"> This is what I have </div>';
var result = $(data).filter("#target").text();
alert("Without targetParent =>" + result); //Get empty result
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

UPDATE : If you want to get the HTML code then get outerHTML property from it from its dom object.

var result = $(data).filter("#target")[0].outerHTML;

var data = '<div id="target"> This is what I have </div>';
var result = $(data).filter("#target")[0].outerHTML;
alert("Without targetParent =>" + result); //Get empty result
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


If there is only single tag then there is no need of filter() method instead get dom object using index.

var result = $(data)[0].outerHTML;

var data = '<div id="target"> This is what I have </div>';
var result = $(data)[0].outerHTML;
alert("Without targetParent =>" + result); //Get empty result