VISHMAY
VISHMAY

Reputation: 709

html stored in javascript variable,how to Update that html inside javascript variable

Here,

var data = '
<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;">    
    <tbody>     
        <tr>
            <td>
                <textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2">&copy; 2016 Vishmay Shah</td>
        </tr>
    </tbody>
</table>
<p>&nbsp;</p>'

I want to update the editor's id to editor1 using jquery within data variable

I can access it using

   $('#editor', Data)[0].id=$('#editor', Data)[0].id+'1';

but I want to save updated HTML in the data variable back.


UPDATE

There will be multiple editors with the same id editor.

Actually, I want to make it unique by appending index.

That is editor0,editor1,..., replace function will replace all editor, so it will not help

  var editors = $('#editor', Data);
    for (var i = 0; i < editors.length; i++) {
        var subeditor = editors[i].id + i;
        editors[i].id = subeditor;
     }

Upvotes: 0

Views: 79

Answers (3)

guest271314
guest271314

Reputation: 1

Updating multiple elements id property can be achieved using :last , .length at .prop(function(name, propertyValue){}) or .attr(function(name, propertyValue){}).

An alternative approach would be to try substituting using same className , e.g.; .editor , for multiple ids beginning with a name and ending in number at multiple elements. Use .length to determine which element currently being processed.

Upvotes: 0

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

If you have more than one with the same ID name, perhaps you need to find it by attribute and replace the old ID name with index like so :

var Data = '<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;">    <tbody>     <tr><td><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea></td>     </tr>       <tr>            <td colspan="2">&copy; 2016 Vishmay Shah</td>       </tr>   </tbody></table><p>&nbsp;</p>';
// this will look the element with ID editor
// and replace element with index
var newElem = $(Data).find('[id="editor"]').attr('id', function(i, old) {
     return old + i;
}).end();
console.log(newElem)

DEMO(inspect element to see the actual ID)

Upvotes: 1

Afsar
Afsar

Reputation: 3124

This will work out:

Data.replace('name="editor"','name="editor1"')

Upvotes: 0

Related Questions