views:

171

answers:

2

If I have HTML content in a variable like so:

var data = "<div id='myid'><div id='subid'>Text</div></div>";

Is there a way to query this using jQuery and selectors? As this, if it were HTML DOM:

var data = $("#myid > #subid").text();
+3  A: 

Use jQuery's context:

$doc = $("<div id='myid'><div id='subid'>Text</div></div>");
var data = $("#subid", $doc).text();

Your example is wrong in that it is trying to access the elements by class (".subid") instead of by id ("#subid") - also, if you have an element's ID, it is not necessary to do something like "#myid > #subid" as since there is only one ID per document (if you're doing things properly, at least) then jQuery can just do the native document.getElementById() to find the element. I tested the above and it works fine.

Paolo Bergantino
Thanks Paolo, that worked like a charm. (Of course, it should be the # prefix, I was a little bit sloppy when typing an example)
Magnus Johansson
+1  A: 

You can use this selector.

var data = "<div id='myid'><div id='subid'>Text</div></div>";
var subIdText = $(data).find('#subid').text();
ichiban