最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript variable to jQuery object - Stack Overflow

programmeradmin3浏览0评论

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>";

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>";
Share Improve this question asked Aug 10, 2011 at 3:05 bobbob 7873 gold badges8 silver badges14 bronze badges 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. – Diodeus - James MacFarlane Commented Aug 10, 2011 at 3:11
Add a comment  | 

2 Answers 2

Reset to default 15
  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)

  1. 暂无评论