How to wrap elements inside of body dynamically - javascript

I need to wrap the elements inside of the body by <div id="wrap"> dynamically, using jQuery/JavaScript. The final result has to be:
<body>
<div id="wrap">
<!-- open div #wrap here -->
<div id="nav">
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
</ul>
</div>
<div id="main">....</div>
</div>
<!-- close div #wrap here, before close body tag -->
</body>
Should I create the div and after add the content that already exists inside body? How can I do it?
Thank you!

First you would want to grab the current HTML and store it in a variable, then the use of the .html()method will do wonders:
$(function(){
var bod = $("body"), current_html = bod.html();
bod.html("<div id=\"wrap\">" + current_html + "</div>");
});

Use .wrapAll() method, as below:
$('body').children().wrapAll("<div id='wrap'>");
JSBin Demo

$(document.body).html("<div id='wrap'>...</div>")

wrapAll should produce several div tags. I would have used wrapInner instead.
$('body').wrapInner('<div id="wrap">');

Related

Using $.get to load elements from another page does not work for root elements? [duplicate]

This question already has answers here:
jQuery.find() ignores root node
(3 answers)
Closed 4 years ago.
I have the following code:
//load nav menu and footer from index.html
$.get('index.html', function(data) {
$('#menuItems').replaceWith($(data).find("#menuItems")); //this works
$('#footer').replaceWith($(data).find("#footer")); //this does not work
});
The code that loads the menu works but the code that loads the footer does not. The only difference I can see is that the #footer is directly under the body element.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- normal head stuff, script references, meta tags, etc. -->
</head>
<body>
<nav>
<ul id='menuItems'>
<li>item</li>
</ul>
</nav>
<div>some content here</div>
<footer id='footer'>stuff</footer>
</body>
</html>
The basic layout above is the same for index.html and the files that pull from it.
In the console if I do some tests, it shows that root elements are not "found":
11:54:12.267 $(data).find('#menuItems').length
11:54:12.270 1
11:54:15.633 $(data).find('#logo-container').length
11:54:15.635 1
11:54:23.001 $(data).find('#footer').length
11:54:23.004 0
11:54:37.008 $(data).find('nav').length
11:54:37.012 0
I really can't think of any other differences. I'll be glad to provide more info if needed.
$(data) doesn't return the entire HTML, only the contents of the <body> element. As a result, <nav> and <footer> become top-level elements in $(data), but find() only searches descendants.
You should wrap it in another element so you can search it:
let data = `<body>
<nav>
<ul id="menuItems">
<li>item</li>
</ul>
</nav>
<footer id="footer">stuff</footer>
</body>`;
$("#button").click(function() {
var contents = $("<div>", {
html: data
});
$('#menuItems').replaceWith(contents.find("#menuItems"));
$('#footer').replaceWith(contents.find("#footer"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul id="menuItems">
<li>old item</li>
</ul>
</nav>
<footer id="footer">old stuff</footer>
<button id="button">Click</button>
Use filter for root level nodes (see jQuery.find() ignores root node)
let response = `<body>
<nav>
<ul id="menuItems">
<li>item</li>
</ul>
</nav>
<footer id="footer">stuff</footer>
</body>`;
console.log('footer : ', $(response).filter('#footer').length);
console.log('menuItems : ', $(response).find('#menuItems').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For a workaround, you can create a custom function like described in this post.

jQuery prepend on clone inserting at unexpected location

I'm trying to copy the contents of a DIV and insert a heading before the copy. However, the heading gets inserted at the wrong point.
var reference = $('#reference').clone().contents();
reference.prepend('<h1>Heading</h1>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reference">
<ul>
<li></li>
</ul>
</div>
I want the heading to go before the <ul> but instead it gets inserted after before the first li.
So it looks like this:
<div id="copy">
<ul>
<h1>Heading</h1>
<li></li>
</ul>
</div>
Instead of this (what I want):
<div id="copy">
<h1>Heading</h1>
<ul>
<li></li>
</ul>
</div>
This is probably a really basic question but a few hours of trying prependTo(), before(), insertBefore() and searching online have not gotten me any closer. Thanks :)
Firstly remove contents() as you want to clone the whole element, not its children. Secondly, create the h1 tag, then use prependTo() to place it at the desired location in the cloned element.
Also note that your current code results in duplicate id attributes in the DOM, which is invalid. I'd suggest making the #reference id in to a class instead. Try this:
var reference = $('.reference:first').clone();
$('<h1>Heading</h1>').prependTo(reference);
$('body').append(reference);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reference">
<ul>
<li>Foo</li>
</ul>
</div>
Use it like this I have tried and It is working fine.
$('#reference').clone().contents().parent().prepend('<h1>Hea‌​ding</h1>')

Move element before the end of BODY

Is there a way to place an html element just before my body end tag, without knowing which tags are before it? In this scenario i don't know that there is a ul list at the end.
Note: I can't use jquery to solve this.
e.g.
<body>
<p id="test">Hello</p>
<script>
document.getElementById("test").MOVE_BEFORE_BODY(); //<-- something like this
</script>
<ul>
<li>...</li>
<li>some random stuff</li>
</ul>
<!-- element should be moved to this position -->
</body>
someElement.appendChild will move an element to the end of someElement.
document.body.appendChild(
document.getElementById("test")
);
Use document.body.appendChild(yourElement)

how we can change the div content by clicking on menu bar without page refresh

<div id="containerright">
<div id="containerrighttop">
<ul>
<li>Content 1</li>
<li>Content 2</li>
<li>Content 3</li>
</ul>
</div>
<div id="containerrightbottom">
</div>
</div>
</div>
** this is my scripting with ajax**
in this i want menubar in horizontal way so that on click on that menu bar the div content on one part of same page get change with out page refresh
<script type="text/javascript">
$(function() {
$("#conatinerright""#containerrighttop").click(function() {
$("#conatinerright""#containerrightbottom" ).load($(this).attr("href"));
return false;
});
});
</script>
$(function() {
$("#containerrighttop a").click(function() {
$("#containerrightbottom").load($(this).attr("href"));
return false;
});
});
Your problems were:
You misspelled #containerright. This part of the selector isn't needed, since the ID of the inner DIV is sufficient.
You used invalid syntax by putting two strings next to each other with no + to concatenate them.
You bound the click handler to #containerrighttop, but it should be bound to the anchors.

How to hide div that is referenced by an anchor href on click with javascript (jQuery)

I have several blocks of text separated into their own divs. I also have several links in a navigation bar that reference these divs with an anchor link. On click, I'd like to hide all other divs except the one referenced by the clicked link. I have:
<div id="navbar">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
</ul>
</div>
So, when I click 'Link 3'. I'd like to hide all divs except #section3.
I'm fine actually hiding/showing each section of text using CSS, but I can't figure out how to use the link's href attribute to reference the div name.
Thanks for your help, and let me know if you need clarification of what I'm asking.
Try this:
$('#navbar a').click(function() {
$('div:not(#navbar)').hide();
$($(this).attr('href')).show();
return false; // You may or may not want this line.
});
You can see an example here.
You can use the anchor's .hash property as a selector, all you need to so is hide the divs you want first, like this:
$('#navbar a').click(function(e) {
$('.container > div').hide();
$(this.hash).show();
e.preventDefault(); //to prevent scrolling
});
This assumes you have the <div> elements you want to show in a container of some sort, like this:
<div class="container">
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<div id="section3">Section 3</div>
<div id="section4">Section 4</div>
</div>
You can test it out here.

Categories