Search code examples
javascripthtmlregexregexp-replace

How can I create div-wrapper with data-attributes from child div using javascript RegExp end replace or another?


There is a string with html:

<div data-class="wrapper-class" data-id="wrapper-id" id="hello-world"> 
    <div data-id="superid" data-class="superclass" class="title">My Title</div data-class data-id> 
    <div class="description">My Desription</div>
</div data-id data-class>
<div data-id="mr-jack" id="mr-brown">Hey!</div data-id>

Around the tags with data-attributes need to create div-wrapper with these data-attrs without "prefix" data-.

There is an example of result string:

<div class="wrapper-class" id="wrapper-id">
    <div id="hello-world">
        <div id="superid" class="superclass">
            <div class="title">My Title</div>
        </div>
        <div class="description">My Description</div>
    </div>
</div>
<div id="mr-jack">
    <div id="mr-brown">Hey!</div>
</div>

Can I do it use javascript RegExp end replace or it do it otherwise? Thanks a lot!


Solution

  • You can do so with this function:

    function wrapAndCleanUpElement(el) {
      var wrapper = document.createElement('div')
    
      for (var data in el.dataset) {
        var dataValue = el.dataset[data]
        switch (data) {
          case 'id':
            wrapper.id = dataValue
            break
          case 'class':
            wrapper.className = dataValue
            break
        }
    
        el.removeAttribute('data-' + data)
      }
    
      el.parentElement.insertBefore(wrapper, el)
      wrapper.appendChild(el)
    }
    

    Programmer discretion is advised.