Sartheris Stormhammer Sartheris Stormhammer - 1 month ago 24
Javascript Question

Jquery selector on a variable

I want to use jQuery to select attributes and elements of some html code, alter them with jQuery, and then append that edited html code in the DOM.

I want to achieve something like this:

var codeExample = $(".stuff").html();
$(codeExample).attr("id").val("2412");
$(codeExample).find("div #foo").attr("rel").val("bar");
$("#element").append(codeExample);


Is that possible? Or I first have to insert the html code in the DOM, and then find it with jQuery and edit it?

Answer
var codeExample = $(".stuff");
codeExample.attr("id", "2412");
codeExample.find("div#foo").attr("rel", "bar");

Though your id and rel are already modified. But if you still want to append it to #element do the following:

$("#element").append(codeExample);
Comments