10

How can I take this javascript variable and

  1. convert it into jQuery object $(myFragment)

  2. 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>";
1
  • 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. Commented Aug 10, 2011 at 3:11

2 Answers 2

15
  1. To convert to jQuery object:

    $(myFragment);
    
  2. To change the id:

    $(myFragment).attr('id', 'fragment1');
    
Sign up to request clarification or add additional context in comments.

1 Comment

how to convert a jQuery object back to JavaScript variable?
3

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/

1 Comment

I'll try this, but I would prefer not to append it to DOM because I am using jQuery Mobile which seems to modify html on the DOM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.