Tuesday, 9 November 2021

jquery contents from a higher level?

I have the following jquery that mostly works:

$("article > p, article > div, article > ol > li, article > ul > li").contents().each(function() {
    if (this.nodeType === 3) {
        strippedValue = $.trim($(this).text());
        doStuff(strippedValue);
    }

    if (this.nodeType === 1) {
        strippedValue = $.trim($(this).html());
        doStuff(strippedValue);
    }
})

The problems comes when (inside doStuff()) I try to replace html tags. Here is a view of my elements:

enter image description here

And I'm trying to replace those <kbd> tags thusly:

newStr = newStr.replace(/<kbd>/g, " <b>");  
newStr = newStr.replace(/<\/kbd>/g, "<b> ");

That doesn't work, and I'm seeing in the debugger that the <kbd> tags are seen as first-class children and looped separately. Whereas I want everything inside my selectors to be seen as a raw string so I can replace things. And I realize I'm asking for a contradiction, because .contents() means get children and their contents. So if I have a selector that is a direct parent of <kbd>, then <kdb> ceases to become a raw string and becomes instead a node that is being looped.

So it seems like my selectors are wrong BUT whenever I try to bring my selectors higher in the hierarchy, immediately I lose textual contents and I end up with a bunch of html with no contents inside the elements. (The screenshot shows good contents, as expected.)

So for example I tried this:

$("article").contents().each(function() {
   ...
}

...hoping that the selector looping would occur a little higher, and thus allow html tags further down to come through as raw text. But clearly I'm lost.

My objective is to simply perform a bunch of string replacements on the contents of the html. But there are 2 challenges with this:

  1. The page contents load dynamically, with ajaxy calls or similar, so full contents are not available until about a second or two after page load.
  2. When I try to grab high-level elements such as body, it ends up devoid of much of the textual contents. The selectors I currently have don't suffer from that problem; those get everything I want BUT then html/xml elements get looped instead of coming through as plain text so that I can perform replacements.

Thanks in advance for any advice.



from jquery contents from a higher level?

No comments:

Post a Comment