Iterating over XhtmlString elements and adding an ID to them


Normally, if you want to render the contents of a XhtmlString then we can just write the code below. Hovever, I need to iterate through the contents of a XhtmlString and add an ID to all <h2 tags>  

            @Html.PropertyFor(m => m.CurrentPage.MainBody)
Edited, Aug 01, 2023 11:07

Here's a blog post about extending XhtmlString and parsing/updating the output content -- different goals, but could be one approach for you:

Aug 01, 2023 17:33

Might be easier to do client side?

$( document ).ready(function() {
// Get the main body and look for h2
    var countItems = 0;
    $('#mainBody').find('h2').each(function () {
// don't show h2 that editors have said to hide
            // add a uniquie id for anchor
            $(this).attr('id', 'autoAnchor' + countItems);
            // add the on this page link
            $('#anchorItems').append('<li><a href="#autoAnchor' + countItems + '">' + $(this).text() + '</a></li>');
    if (countItems > 0) {
        // if we found items show the on this page section
Aug 04, 2023 0:16
Laurent - Aug 04, 2023 6:28
Thanks Paul! I ended up doing it in the client side with plain JavaScript since I could not make a service for it. I was afraid that doing it that way would affect the cumulative layout shift (and generally I try to avoid using JS ¯\_(ツ)_/¯), but apparently is does not.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.