Search code examples
javascriptjqueryprototypejs

prototype.js wrap each h3 tag with span


excuse any ignorance but I'm a regular jQuery user and have to add some code on a prototype.js website. I've checked through the docs but am still none the wiser as to how I can simply wrap each h3 element in a sidebar with a span tag.

I have tried two options, neither of which work…

$$('.ipsLayout_right h3').wrap(span);

and

$$(".ipsLayout_right h3").each(function(element) {
    element.replace("<h3><span>" + element.innerHTML + "</span></h3>");
});

Can anyone help get this sorted?

Thanks


Solution

  • PrototypeJS doesn't have jQuery's set-based approach. The closest it comes is its invoke function, which lets you "invoke" a method on all elements in an Enumeration:

    $$('.ipsLayout_right h3').invoke("wrap", "span");
    

    Live Example - but see note below


    Side note: It's invalid to wrap an h3 in a span. The content model of span is phrasing content (like the text in a paragraph), but h3 can only be used where flow content (like entire paragraphs) is expected.

    If you want to wrap the contents of the h3, allowing for the possibility that those contents may well be text nodes and not elements, then I'm pretty sure you have to do a lot more work:

    $$('.ipsLayout_right h3').each(function(h3) {
      var span = new Element('span');
      while (h3.firstChild) {
        span.appendChild(h3.firstChild);
      }
      h3.appendChild(span);
    });
    

    Live Example