开发者

javascript variable to jQuery object

开发者 https://www.devze.com 2023-03-27 13:29 出处:网络
How can I take this javascript variable and convert it into jQuery object$(myFragment) change the id attribute from \"fragment\" to \"fragment1\" ?

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. To convert to jQuery object:

    $(myFragment);
    
  2. 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/

0

精彩评论

暂无评论...
验证码 换一张
取 消