Devdatta Tengshe Devdatta Tengshe - 1 month ago 10
HTML Question

How to parse HTML & replace Tags in a String using jQuery?

I have a string like this (unminified here for easy reading):

var input='<div id="container" style="max-width: 310px;">
<div class="popupheadermap">
<b>YFC</b>
</div>
<input checked="checked" id="tab-1" name="tab-group" type="radio">
<label for="tab-1">Administration</label>
<input id="tab-2" name="tab-group" type="radio">
<label for="tab-2">Information</label>
<div id="content">
<div id="content-1">
<td>Id</td>
<td class="tablerow">1252</td>
</div>
<div id="content-2">
<td>Type</td>
<td class="tablerow">Gym</td>
</div>
</div>
</div>
<div id="EditContainer">
<button class="editMarker" id="1252"><i aria-hidden="true" class="fa fa-pencil editicon"></i>Edit Location</button>
</div>';


Using jQuery I want to replace the contents of the
EditContainer
div, so that it becomes:

<div id="EditContainer">
<button id="1126_1" class="saveCancel"><i class="fa fa-floppy-o editicon" aria-hidden="true"></i>Save Edit</button>
<button id="1126_2" class="saveCancel"><i class="fa fa-ban editicon" aria-hidden="true"> </i>Cancel Edit</button>
</div>


But when I use find, with
$(input).find('#EditContainer')
, I get an empty ouput.

How do I parse this string, and replace the contents of the
EditContainer
div?

Answer

The issue you have is that the #EditContainer element is in the root level of the string, so you need to use filter(), not find(). Try this:

var input = '<div id="container" style="max-width: 310px;">' +
    '<div class="popupheadermap">' +
        '<b>YFC</b>' +
    '</div>' +
    '<input checked="checked" id="tab-1" name="tab-group" type="radio">' +
    '<label for="tab-1">Administration</label>' +
    '<input id="tab-2" name="tab-group" type="radio">' +
    '<label for="tab-2">Information</label>' +
    '<div id="content">' +
        '<div id="content-1">' +
            '<td>Id</td>' +
            '<td class="tablerow">1252</td>' +
        '</div>' +
        '<div id="content-2">' +
            '<td>Type</td>' +
            '<td class="tablerow">Gym</td>' +
        '</div>' +
    '</div>' +
'</div>' +
'<div id="EditContainer">' +
    '<button class="editMarker" id="1252"><i aria-hidden="true" class="fa fa-pencil editicon"></i>Edit Location</button>' +
'</div>';

var $input = $(input);
$input.filter('#EditContainer').html('<button id="1126_1" class="saveCancel"><i class="fa fa-floppy-o editicon" aria-hidden="true"></i>Save Edit</button><button id="1126_2" class="saveCancel"><i class="fa fa-ban editicon" aria-hidden="true"> </i>Cancel Edit</button>');
$input.appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>