Jacob
Jacob

Reputation: 69

JQuery modify body content after div

I have my code which have a header. I want to modify the whole page except the header. I need to use html() and not append/prepend/etc.

Code looks like this:

<body>
    <div class="header">
        HEADER
    </div>
    <!-- MODIFY THIS -->
</body>

I have tried this but no luck $("body .header:after").html("TEST");

Is it possible ?

PS: Dont add any div. I just want to select and modify whole content after the header class.

JSfiddle

Upvotes: 0

Views: 772

Answers (4)

Allan Empalmado
Allan Empalmado

Reputation: 943

.html() is replace all element with new element.So you can try jQuery insertAfter method.

$( "<p>Your HTML Code Here</p>" ).insertAfter( ".header" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="header">
        HEADER
    </div>
    <!-- MODIFY THIS -->
</body>

Upvotes: 0

Trung Le Nguyen Nhat
Trung Le Nguyen Nhat

Reputation: 646

My solution:

$("body").html(document.getElementsByClassName("header")[0].outerHTML + "TEST");

Hope this can help.

Upvotes: 0

Cobus Kruger
Cobus Kruger

Reputation: 8605

You cannot use :after in jQuery and your problem is that there isn't actually anything to select if you don't select the header - your entire document is the body tag, followed by the header.

If there is nothing to select, there is nothing to use html() on.

You will need to add at least one div, or insert the header as part of your html() for the body:

$("div:not(.header)").html("Body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="header">
        HEADER
    </div>
    <div><!-- MODIFY THIS --></div>
</body>

Or you could just use append() because it was designed to do exactly this:

$("body").append("<div>Body</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="header">
        HEADER
    </div>
    <!-- MODIFY THIS -->
</body>

Upvotes: 0

Sooraj
Sooraj

Reputation: 10567

You can do something like this. Get the content in the header , and then use it to populate entire body tag.

jQuery(document).ready(function() {
 
  var content = jQuery(".header").text();
  jQuery("body").html("<div class='header'>"+content+"</div>" + 'modified content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="header">
    HEADER
  </div>
  Some random content
</body>

Upvotes: 1

Related Questions