How can I take this javascript variable and
convert it into jQuery object $(myFragment)
change the id attribute from "fragment" to "fragment1" ?
myFragment = "\ <div id='fragment'>\ <input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\ value='' />\ <input type='hidden' id='preGroup' name='GRP' value='' />\ </div>";
How can I take this javascript variable and
convert it into jQuery object $(myFragment)
change the id attribute from "fragment" to "fragment1" ?
Share Improve this question asked Aug 10, 2011 at 3:05 bobbob 7873 gold badges8 silver badges14 bronze badges 1myFragment = "\ <div id='fragment'>\ <input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\ value='' />\ <input type='hidden' id='preGroup' name='GRP' value='' />\ </div>";
- Until you insert it into the DOM it is merely a string. Treat it as a string (you can use .replace) , or insert it onto the DOM and manipulate it with JS or jQuery. – Diodeus - James MacFarlane Commented Aug 10, 2011 at 3:11
2 Answers
Reset to default 15To convert to jQuery object:
$(myFragment);
To change the id:
$(myFragment).attr('id', 'fragment1');
To convert the string to HTML element pass it to jQuery function as parameter and it will return you a html element wrapped as a jQuery object. Then you can use all the regular jQuery functions to change the element.
Try this:
var myFragment = "\
<div id='fragment'>\
<input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\
value='' />\
<input type='hidden' id='preGroup' name='GRP' value='' />\
</div>";
var $myFragment = $(myFragment).appendTo("body");
$myFragment.attr("id", "new-id");
$("#new-id").text("It works!!!");
Working example: http://jsfiddle.net/xhC7D/