Search code examples
javascriptjqueryhtmlstylingprepend

Prepend dynamic content to multiple elements with jQuery


Sure this is an easy one but finding it hard to search for an answer due to not knowing the exact words to search for :/

also if theres a better way of doing this please do tell me ;)

basically I'm generating some div boxes with various contents and titles

so in my html pages I have:

<div class="itdSec" data-title="What is This">
    This is a magical div box with some stuff in it
</div>

in my js file I have

$(".itdSec").prepend("<div class='itdSecTit'>" + this.data("title") + "</div>");

The intent is to add a div to the top of that div with the contents of the data-title arribute

the "this" is causing the errors as this is still the main page. and using $(".itdSec") in its place returns the first one each time.


Solution

  • This works:

    $(function(){
      $(".itdSec").prepend(function() {
        return "<div class='itdSecTit'>" + $(this).data("title") + "</div>";
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="itdSec" data-title="What is This">
        This is a magical div box with some stuff in it
    </div>

    alternatively you can do this:

    $(function(){
      $(".itdSec").each(function() {
        $(this).prepend("<div class='itdSecTit'>" + $(this).data("title") + "</div>");
      }); 
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="itdSec" data-title="What is This">
      This is a magical div box with some stuff in it
    </div>