Html – How to find html elements that contain specific text in an html comment


I'm trying to use jQuery to identify <td> elements which contain specific HTML comment text. The standard ":contains" selector doesn't seem to be looking into the comments. My context here is that I want to dynamically add some content to that same td element. Here's a sample of the target td:

<TD valign="top" class="ms-formbody" width="400px">
        <!-- FieldName="Title"
            <span dir="none">
        <input name="ctl00$m$g_0b1e4ca3_9450_4f3e_b3af_8134fe014ea5$ctl00$ctl04$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField" type="text" maxlength="255" id="ctl00_m_g_0b1e4ca3_9450_4f3e_b3af_8134fe014ea5_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField" title="Title" class="ms-long" /><br>


This html is generated by SharePoint as part of a new list item form, and I really want to find the td in my document whose "FieldInternalName" in the comment matches some text string. How can I use jQuery (or any javascript would really be okay) to best find these td elements?

Best Solution

You could grab the innerHTML of the element and run a regular expression over it.


// HTML: <div id="myElement">Lorem <!-- a comment --> ipsum.</div>

var element = document.getElementById('myElement');
alert(element.innerHTML); // alerts "Lorem <!-- a comment --> ipsum."
// here you could run a regular expression

Update: a more comprehensive example (with jQuery):

var tds = $('td'), match;
tds.each(function(index, element) {
    match = $(element).innerHTML.match(/FieldInternalName="(^["])"/);
    if (match) alert(match);