run jQuery on variable and not on document
Do you know if it's possible to run jQuery on a variable that contains html and not just on the document itself.
Example:
bg.inspectorGetRawHtml = function(){
var c = jQuery("#bg-admin-inspect-wrapper").html();
jQuery(".bg-admin-inspect-state", c).remove();
console.debug(c);
}
So bascially, reading a segment of the pages html into a variable and then performing jQuery manipulation on that string.
If I console.debug the actual jQuery remove, it seems like does the matching, but the var is not manipulated. I know jQuery relies on the DOM, and maybe that's开发者_开发技巧 why it's not working, but if anyone has any insight on this.... Edit After lonesomeday's suggestion, here is the code I ended up with:
bg.inspectorGetRawHtml = function(){
var c = jQuery("#bg-admin-inspect-wrapper").clone();
jQuery(".bg-admin-inspect-state", c).remove(); //The ,c specifies what element to work on.
console.debug(c.html());
}
The function you need is $().detach:
bg.inspectorGetRawHtml = function(){
var c = jQuery("#bg-admin-inspect-wrapper").detach();
console.debug(c);
}
This will remove the selected element from the DOM and allow you to perform jQuery operations on it.
Edit You can also create a piece of HTML from a string and turn it into a jQuery selection and work with it. For instance
$(document).ready(function() {
var newText = '<div><p>Some text here</p><img src="image.png" /></div',
$newDiv = $(newText);
$newDiv.addClass('someClass');
$('body').html($newDiv);
});
This creates a new div with a paragraph of content and an image, adds the class "someClass" to the div and replaces the content of the page with the new div.
精彩评论