Wrap div generated by PHP with another div with CSS class

2

My question is about the following. Now I have this in a .php file:

<div class="uno">
   <?php if( function_exists('number') ) { number('tres'); ?>
</div>

The PHP code that is in the middle generates a <div class="tres"> , like this:

<div class="uno">
   <div class="tres"></div>
</div>

Well, what I'm looking for is: if the <div class="tres"> is generated, that it is wrapped with another <div> with a CSS class. The result should be this:

<div class="uno">
   <div class="dos"> ← La "envoltura" que necesito
      <div class="tres"></div>
   </div>
</div>

I can not put the <div class="dos"> directly in my .php file, so I need it to appear only if it's <div class="tres"> .

Can this be done with JavaScript? How?

    
asked by Alex 17.09.2018 в 08:16
source

1 answer

2

To do what you want you should check if the selector ' div.uno div.tres ' exists (a <div> with class uno that has a child that is a <div> with class three) making use of document.querySelector() and if so, create <div> with document.createElement() and change the class to dos with Element.setAttribute() and finally make the change of nodes with Node.appendChild() and Node.removeChild() :

<div class="uno">
   <div class="tres">hola</div>
</div>
<script>
let tres = document.querySelector('div.uno div.tres');
/* ¿Existe el selector deseado? */
if (tres !== null) {
  /* Obtenemos el div padre */
  let uno = tres.parentNode;
  /* Creamos un nuevo elemento div */
  let dos = document.createElement('div');
  /* Le cambiamos la clase a "dos" */
  dos.setAttribute('class', 'dos');
  /* Quitamos el nodo tres como hijo del uno */
  uno.removeChild(tres);
  /* Agregamos como hijo de uno al dos */
  uno.appendChild(dos);
  /* Agregamos como hijo del dos al tres */
  dos.appendChild(tres);
}
/* Mostramos el resultado final */
console.log(document.querySelector('div.uno').outerHTML);
</script>
    
answered by 17.09.2018 / 08:28
source