问题
I am trying to wrap content in a div but the problem is the html page is not editable so I am trying other way, using jQuery to wrap all the content in a div
following is the html
structure
$(document).ready(function() {
$("hr").before("<div class=wrapElement>");
$("#disqus_thread").before("</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<h4>Title Here</h4>
<p> </p>
<p> </p>
<p> </p>
<div id="disqus_thread"></div>
Problem opening div
is placed on correct position, but closing div is not on correct position, it should be above div id="disqus_thread"
but its not there, how do I get it placed on this position?
jQuery version is 1.12.4
thanks in advance
回答1:
Use nextUntil() method to get all elements upto the div and use wrapAll() method to wrap them using a div
element.
$(document).ready(function() {
$("hr").nextUntil("#disqus_thread") // get elements from hr upto the previous element of #disqus_thread
.wrapAll("<div class=wrapElement></div>"); // wrap all elements using div
});
$(document).ready(function() {
$("hr").nextUntil("#disqus_thread").wrapAll("<div class=wrapElement></div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<h4>Title Here</h4>
<p> </p>
<p> </p>
<p> </p>
<div id="disqus_thread"></div>
回答2:
Or, you can just use built-in jQuery functions:
Here's a fiddle: https://jsfiddle.net/uhr4kuk6/5/
$(document).ready(function() {
$('hr').remove();
$('h4').wrap('<div class="wrapElement">').prepend('<hr>');
$('p').each(function() {
var getContentWithTags = $(this).clone();
$('.wrapElement').append(getContentWithTags);
$(this).remove();
})
});
.wrapElement {
background: red;
padding-top: .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<hr>
<h4>Title Here</h4>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<div id="disqus_thread"></div>
回答3:
If you have a container you can use jQuery wrapInner() method, easly :
$( "body" ).wrapInner( "<div class='wrapElement'></div>");
回答4:
Suppose your content is inside the body tag:
var mainhtml= $('body').find('*').not('#thread_content').html()
$('#thread_content').html(mainhtml);
回答5:
Try this..
<hr>
<h4>Title Here</h4>
<p> </p>
<p> </p>
<p> </p>
<div id="disqus_thread"></div>
$(document).ready(function() {
$("body").wrapInner("<div class=wrapElement></div>");
});
来源:https://stackoverflow.com/questions/40625638/wrap-content-in-a-div-using-jquery