Is there a way to query HTML/XML content from a va

2019-08-16 15:36发布

问题:

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();

回答1:

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.



回答2:

You can use this selector.

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