Reputation: 2808
I am implicitly creating some HTML on the fly, to be injected into the DOM.
However, the block of HTML I have to be injected, I need to use jQuery to select an element and do something with it.
I know $("#element")
selects from the active DOM, but is there anyway to provide jQuery a chunk of HTML as a string and have it select from that instead?
Like for example, heres some pseudo code
var html = '<div><span id="selectMe"></span></div>';
// below obviously doesn't work as it'd select from the active DOM
var html = $("#selectMe").html("injected");
Is there a way to get jQuery to not select from the DOM but from a variable containing HTML?
Upvotes: 0
Views: 55
Reputation: 57105
Try
var html = '<div><span id="selectMe"></span></div>';
var html_var = $(html);
html_var.children('#selectMe').html("injected");
Reference
Upvotes: 1
Reputation: 388316
you can use
var html = '<div><span id="selectMe"></span></div>';
var $html = $(html);
$html.find('#selectMe').html("injected");
Note: The string html
will not get updated with the new markup, but the dom structure holded by $html
will contain the update
Upvotes: 1