Is it possible to add something with innerHTML before/after the nth child of <body>?
e.g.:
<html>
<head></head>
<body>
<div id="first">First</div>
<div id="second">Second<div id="second_sub"></div></div>
<div id="third">Third</div>
</body>
</html>
I can add at the beginning with body.innerHTML = html + body.innerHTML and at the end with body.innerHTML += html but how to add, for example, before the second <div>?
I don't want to use replace on <div id="second"> as the source changes and the insert should be done at random. Is there a solution with innerHTML or do I need to switch to Dom Nodes? Would be slow in old browsers :(
You are probably looking for the insertBefore method. It will insert a child before the given element. Alternatively there's the appendChild method which will always push elements on the beginning of the given element.
Examples:
<body>
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
Let's assume we're inserting a new element stored in the var newElem:
document.insertBefore(newElem, document.getElementById("elem2")) will give:
<body>
<span id="elem1">Hello</span>
<!-- New element here! -->
<span id="elem2">World</span>
</body>
document.appendChild(newElem) will give:
<body>
<!-- New element here! -->
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
I'm using this by now (Thanks to ajax333221):
e = document.createElement('div');
e.innerHTML = '<div>... huge content with several sub elements ...</div>';
document.body.insertBefore(e, document.body.childNodes[2]);
This is a combination of both techniques. With this I'm able to use the fast .innerHTML without extremely blowing up the code with createElement(), setAttribute(), etc.
Other solutions are welcome.
Related
I want to replace content within element in JavaScript but I cannot use innerHTML and jQuery.
For example:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
I want to replace everything between <div id="MyID"> and </div>.
Like via innerHTML which I sadly cannot use:
document.getElementById('MyID').innerHTML = document.getElementById('MyID').innerHTML.replace(/you/, 'you');
Which will be:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
How to do it?
I tried things like appendChild and removeChild but I still cannot figure it out.
For appendChild, you should append a dom entity
Use remove() to clear the existing content and then insertAdjacentHTML() to enter the new content. Here is your code sample as an example.
<div id="MyID">
<span id="MyID2">
<b>Hi,</b> how are you?<br/>
I am fine.
</span>
</div>
<button onclick="myFunction()">Insert a paragraph</button>
<script>
function myFunction() {
var a = document.getElementById("MyID2");
a.remove();
var b = document.getElementById("MyID");
b.insertAdjacentHTML('afterbegin', '<b>Hi,</b> how are you?<br/>I am fine.');
}
</script>
I want to add html tag without ending tag like that <div class="bottom-widget"> . For that I use jQuery prepend() method but full tag was added by this !
Html Markup -
<div class="widget">
<h2>this is content 1</h2>
</div>
</div>
Javascript Code :
$(".widget").prepend('<div class="bottom-widget">');
Perhaps you are looking for wrapInner function.
And you code will be:
$(".wrapInner").wrapInner("<div class='bottom-widget'>");
I assume you need correct html so after this opening tag you will have another with closing one. For this reason you can use jQuery wrapInner function (http://api.jquery.com/wrapinner/)
First extract(or create) the element you want to be wrapped in your bottom-widget element, than create bottom-widget element and insert above-mentioned element into it.
$(".widget").prepend("<div class='bottom-widget'></div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<h2>this is content 1</h2>
</div>
I have a div tag with class divstudent, lets say this is div1 tag. Now I want to create another div tag div2 dynamically below this div1 tag, not inside of the div1 tag. I want to create outside of div1 tag using javascript. How can I do that?
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
Try something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function () {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function () {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
Since this is tagged jquery, just use .after()
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
There are many ways to do this. One significant difference in methods is if you choose to create the elements first using Document.createElement() and then insert the elements, or create and insert the elements in one step using one of the methods that allows you to insert HTML text.
Because it is simpler, but not necessarily better, the examples below show creating and inserting the two <div> elements in a single step using methods that allow inserting HTML text into the DOM.
JavaScript:
One is to use insertAdjacentHTML() and specify that it is to be inserted afterend of the element you are using.
document.querySelector() is used to find the first <div class="divstudent">. Then insertAdjacentHTML() is used to add the additional <div> elements. Element.removeAttribute() is then used to remove the class="divstudent". Note: if we had just wanted to set teh class to something different, even '', then we could have used Element.className.
NOTE: In this answer, text identifying each <div> has been added to the <div>s so there is something visible in the examples in this answer.
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
jQuery:
While your question is tagged jQuery, a comment you posted implies you are just using JavaScript. Thus, I am not sure if jQuery works for you.
If you want to use jQuery, then you can use .after() to add the <div> elements. You can then use .removeAttr() to remove the class="divstudent".
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
You create a new div (in js), then just append your newDiv, after the target div. Something along the lines of in vanilla js:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);
I have a setInterval function which replaces text within a particular div element every second. I also have text in the body which I want to keep.
What is the easiest way to preserve the text in a document without .innerHTML overriding the whole document?
<html>
<div id="timer" </div>
<script>
window.onload = setInterval(function(){refreshTime()},1000);
function refreshTime()
{
document.getElementById("timer").innerHTML = ""+DAYS+" Days:"+HOURS+" Hours:"+(minutes)+" Minutes:"+seconds+" ;
time = time+1;}
</script>
<body>
<p>
sOME TEXT I WANT TO KEEP ON
</p>
</body>
I've removed a lot of unncessary code to make it easier for you guys to read. I hope you guys understand what I'm asking. This is my first time on SO
<div id="timer" </div>
change it to <div id="timer"></div>
And paste it in body tag
I would like to insert a couple of opening DIV tags after the H1 element on a page, without inserting the corresponding closing tags (since the closing tags are contained in an included footer file which I don't have access to).
i.e.
Existing code:
<body>
<h1>Heading One</h1>
... page content...
</div>
</div>
</body>
New code:
<body>
<h1>Heading One</h1>
<div id="foo">
<div id="baa">
... page content...
</div>
</div>
</body>
DOM methods insert the div as a complete (closed) element, 'createTextNode' inserts escaped characters and 'innerHTML' needs an element to insert into. Have even tried to insert a script element with document.write without any luck.
Any ideas (jQuery would be fine)?
Update
The following worked:
document.body.innerHTML = document.body.innerHTML.replace('</h1>','</h1><div id="foo"><div id="baa">')
As pointed out by Asad the solution (which now seems obvious of course) is to use string methods on the HTML rather than DOM methods.
If you're dealing with DOM manipulation, use DOM manipulation methods. If you're dealing with HTML manipulation, use string manipulation methods.
h1.parentElement.innerHTML = h1.parentElement.innerHTML.replace("<h1>Heading One</h1>","<h1>Heading One</h1><div><div>");
i think this will answer your question, it is all about valid XML formation.
http://www.w3schools.com/xml/xml_syntax.asp
Forget DOM methods, insert it as a string using .replace().
Your approach is fundamentally wrong. The browser parses the DOM as it sees it, and automatically closes any tags that ought to be closed. It's impossible to use JavaScript to insert only the opening tag.
You say "the closing tags are contained in an included footer file which I don't have access to." Closed tags that haven't been opened are ignored, so as far as the DOM parser is concerned, those closing tags don't exist.
Your solution is either:
Put the opening tags in a header, or somewhere else on the server-side, or
Use JavaScript to grab ALL the following DOM elements, including the footer, and .wrap() them all in the desired divs.
This kind of practice seems a bit unorthodox, but perhaps something like this would help.
Existing HTML
<h1 id="testH1">Test H1</h1>
<div id="existingDiv">
<div id="existingDivContent">Existing Div Content</div>
</div>
New HTML
<h1 id="testH1">Test H1</h1>
<div id="newDiv">
<div id="existingDiv">
<div id="existingDivContent">Existing Div Content</div>
</div>
</div>
JS
The javascript is fairly rudimentary, but I think the concept can be applied to safely and properly achieve your goal.
$(document).ready(function() {
//-- parent node you wish to copy
var existingDiv = $('#existingDiv');
//-- new parent div node
var newDiv = $('<div id="newDiv">');
//-- where we want to insert the new parent node
var testH1 = $('#testH1');
//-- stuff our previous parent node into our new parent node
newDiv.html(existingDiv);
//-- insert into the DOM
testH1.after(newDiv);
});
http://jsfiddle.net/8qzvN/