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>";
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.
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.
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).
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.
To 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With