Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable to jQuery object

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>";
like image 832
bob Avatar asked Aug 10 '11 03:08

bob


People also ask

Can I use JavaScript variable in jQuery?

In the following examples, it can be seen that we have used the values stored in JavaScript Variables are used inside the jQuery Selectors. Example 1: The concatenation technique can be applied in order to use the values stored in JavaScript variables.

Can I put variable in jQuery selector?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

How do you object in jQuery?

Another way to make objects in Javascript using JQuery , getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be: var box = {}; // my object var boxes = []; // my array $('div. test'). each(function (index, value) { color = $('p', this).

Which methods return the element as a jQuery object?

The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.


Video Answer


2 Answers

  1. To convert to jQuery object:

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

    $(myFragment).attr('id', 'fragment1');
    
like image 144
bfavaretto Avatar answered Oct 03 '22 10:10

bfavaretto


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/

like image 20
Chandu Avatar answered Oct 03 '22 10:10

Chandu