Search code examples
javascriptjqueryhtmlcanvasgrapesjs

Add attribute to Child element in Grape Js?


I'm working in grape js for the long time .

Now I face some issue init.

Issue:

This is the component I try to add in Editor.

<div class="page">
      <div class="col1"></div>
      <div class="col2"></div>
 </div> 

After adding those components I try to add some computed values to the elements like this,

element.on('component:add',function(ele){
   ele.addAttributes({
     'data-top' : topOffset,
     'data-left' : leftOffset,
   });

   editor.render();// For render Updated html
});

But, this code only update the .page component only.

How Can I add those attr into .col1,.col2 elements inside .page component ?


Solution

  • I read the documentation and there does not seem to be a straightforward way to get what you want. However you can do something like below snippet. It iterates over all child elements and adds the attributes to them.

    editor.on('component:add', function (ele, argument) {
       ele.setAttributes({
         'data-top' : 10,
         'data-left' : 20,
       });
    
       ele.attributes.components.models.forEach(function(item){
          if(item.attributes.tagName == 'div') {
             item.setAttributes({
               'data-top' : 10,
               'data-left' : 20,
             })
          }
       })
    
       editor.render();// For render Updated html
    })