skip to Main Content

So I’ve browsed around a lot looking for an answer, but I couldn’t find anything that meets what I’m looking for.

So I’m editing a forum, that’s very locked in terms of adding new css classes to customize the look. So, I want to set it so, I can add a div class before the fixed class.

Example of the fixed class:

<div class="titlemedium"> </div>

What I’m trying to do using Jquery:

<div class="divthatcomesbefore"> <div class="titlemedium"> </div> </div>

Basically, I want the divthatcomesbefore to auto wrap around the titlemedium using JS, and I have no idea how to do it. Please help.

This is the script I tried to write, needless to say, it didn’t work.

<script> $(".divthatcomesbefore").before('<div class="titlemedium"></div>'); </script>

2

Answers


  1. You might want to use jQuery’s .wrap() method

    $(".titlemedium").wrap(`<div class="divthatcomesbefore" />`);
    div {
      padding: 1rem;
      outline: 1px solid #000;
    }
    
    .titlemedium {
      background: gold;
    }
    
    .divthatcomesbefore {
      background: red;
    }
    <div class="titlemedium"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    or in plain JavaScript:

    // DOM utility functions:
    const els = (sel, par = document) => par.querySelectorAll(sel);
    const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
    
    // Task:
    els(".titlemedium").forEach((elTitleMedium) => {
      const elWrapper = elNew("div", {className: "divthatcomesbefore"});
      elTitleMedium.replaceWith(elWrapper);
      elWrapper.append(elTitleMedium);
    });
    div {
      padding: 1rem;
      outline: 1px solid #000;
    }
    
    .titlemedium {
      background: gold;
    }
    
    .divthatcomesbefore {
      background: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="titlemedium"></div>
    Login or Signup to reply.
  2. Does this help?

    const titlemedium = document.querySelector('.titlemedium');
    const wrapper = document.createElement('div');
    wrapper.className = 'divthatcomesbefore';
    titlemedium.replaceWith(wrapper);
    wrapper.appendChild(titlemedium);
    .titlemedium {
      border: 10px solid red;
      padding: 10px;
    }
    
    .divthatcomesbefore {
      border: 10px solid blue;
    }
    <div class="titlemedium"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search