Try our conversational search powered by Generative AI!

Iterating over XhtmlString elements and adding an ID to them

Vote:
 

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)
#306039
Edited, Aug 01, 2023 11:07
Vote:
 

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

https://blogs.perficient.com/2022/10/07/custom-xhtmlstring-render-service-force-absolute-url-for-images/

#306044
Aug 01, 2023 17:33
Vote:
 

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
        if(!$(this).hasClass('hideFromAuto')){
            // 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>');
            countItems++;
        }
        });
    if (countItems > 0) {
        // if we found items show the on this page section
        $("#anchor-links").removeClass('is-hidden');
    }
});
#306215
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.