Javascript: Dynamic Generation of a Div - javascript

I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?
I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.

Clone Node
var clone = myDiv.cloneNode();
Example (live demo):
HTML
<div>
<input type="button" onclick="functionClone(this);" value="Dolly"/>
<input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>
Javascript:
functionClone = function(subject){
var clonenode = subject.cloneNode(true);
subject.value = subject.value + '\'s been cloned!';
subject.disabled = true;
insertElementAfter(subject, clonenode);
}
insertElementAfter = function(subject, newElement){
subject.parentNode.insertBefore(newElement,subject.nextSibling);
}

To append an element below your div use this:
subject.parentNode.appendChild(clonenode)

Related

How to add to the content of a div without deleting it's original content using javascript

I was making a quiz site and when I came to the point when I was making a button to show you the correct answer of your mistake I used document.getElementById but it always erased the rest of the answers that was written by the same method.
here is a snippet of my javascript code
if (mistakes > 0) {
if (document.getElementById('wrongAnswer1').checked === true ||
document.getElementById('wrongAnswer2').checked === true) {
document.getElementById('mistakesDiv').innerHTML =
document.getElementById('mistakesDiv').innerHTML +
"<br>" +
"question 1's correct answer is" +
document.getElementById('correctAnswer1').value;
}
}
Design your html div as:
<div id="contentId">
......
......
</div>
And your javascript like:
var div = document.getElementById('contentId');
div.innerHTML += 'your content';
You can separate the content which you are adding dynamically from existing content because when you are updating innerHTML it will update all the content inside the selected element.
So one solution is take a parent div(the div which you will select for adding new child) and add child divs(dynamically added div) inside that for each correct answer.
If you want to give some id to dynamic div you can use a counter or question id for which this new child div has got added.
For adding new children to "parent" you can use "appendChild" method.
It will be something like this:
<div id="parent">
<div id="child1">Here goes the correct answer</div>(button element will also work fine)
</div>
I have created a fiddle for your scenario please have a look:
https://jsfiddle.net/jbw7ku15/
In order to append without changing the actual html, for example you want to give the user the ability to add fields to a form that he is in process of filling. You can use insertAdjacentHTML
var html = "<br>" + "question 1's correct answer is" + document.getElementById('correctAnswer1').value;
document.getElementById('mistakesDiv').insertAdjacentHTML("afterend",html);

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

Javascript: Create a new div in <body> tag

This is going to be hard to explain but I will do my best. I want to write a Javascript function that takes two parameters (title, content) and creates a <div> tag in the <body> tag. The <div> tag should look like this.
<div>
<h2>title</h2>
<p>content</p>
</div>
My javascript code looks like this:
function addElement (title, content) {
var newDiv = document.createElement("div");
var newH2 = document.createElement("h2");
var title = document.createTextNode(header);
newH2.appendChild(title);
var p = document.createElement("p");
var post = document.createTextNode(entry);
p.appendChild(post);
newDiv.appendChild(newH2);
newDiv.appendChild(p);
// Missing codes here...
}
I dont know how to finish my method. Because of I have almost hundreds of tags inside my page and I want this new tags (when a user makes a new input) will appear on same place somewhere in the middle of the html code page in order to keep things organized.
If you would like to use jQuery take a look at this fiddle: http://jsfiddle.net/panpymq2/
In my fiddle I am binding to a button press. Then I call a method that appends new generated html to the body of the page. You can enter change where you are appending the new HTML with CSS3 selectors. just modify the $("insert selector there").append...
UPDATE
As per the new requirements I have updated my fiddle: http://jsfiddle.net/panpymq2/1/
I now prepend the new html to the document.
You already know how to add elements as children of other elements. That's what you used to add the h2 and p to the div. You could use the same appendChild to add the div to the document:
document.body.appendChild(newDiv);
But you don't want it at the bottom of the page--you want it "in the middle of the html code page". One straightforward way to do this is to add the newDiv to a container that's in the right place, in the middle of the page.
You'd first create this container in the page HTML:
<!doctype html>
<body>
<p>stuff before</p>
<div id="container"></div>
<p>stuff after</p>
</body>
Then, finish off addElement with:
document.getElementById('container').appendChild(newDiv);
One way would be if addElement took a third parameter which is the sibling/parent you want to insert your new element next to/within.
function addElement(title, content, target) {
...
target.insertAdjacentElement('afterend', newDiv);
// or
target.appendChild(newDiv);
}
I think this is as much of an HTML as a CSS problem. I've had the same issue.
One way of solving this problem is to make an (extra) container <div> as follows:
<div id="outer_container_elems">
<div id="inner_container_elems">
...
</div>
</div>
And append to inner_container_elems
Hope this helps!

Wrapping a jquery validate span.error with nested divs

Heyo. This is my first stack overflow post because I am stumped and not finding many people who are trying to accomplish the same thing. I've tried using jquery .before(), .after(), and .wrap() to resolve this. I was initially using css :before and :after pseudo-elements, but as that won't work for legacy browsers, I've decided to use jquery.
I already have several forms on several pages with validation working. The error messages vary in length. We were using a static, one size background image on the default span element, so content was bleeding out on longer error messages. I built a flexible rounded corner series of nested divs to allow the error box to grow or shrink dynamically. The html I want to output is:
<div class="errorWrap">
<div class="errorTop"><span></span></div>
<div class="errorContent">
<span class="error">This is an error</span>
</div>
<div class="errorBottom"><span></span></div>
</div>
Here's an example of a solution I tried, but I'm still pretty new to javascript.
$('.error').before('<div class="errorWrap"><div class="errorTop"><span></span></div><div class="errorContent">');
$('.error').after('</div><div class="errorBottom"><span></span></div></div>');
Correct me if I'm wrong, but I think that I have the right idea with the jquery. But it's just kind of sitting there, not in any function being called. So I imagine that since the code isn't re-executing, it just doesn't show up. Is there an appropriate function to wrap this in? I'm certain I'm just not attacking this from the right direction. Any help is super appreciated.
the plugins "before" and "after" dont take html as string. you cannot start a div in one and close it in an other.
Either you take your current html and generate a new html string which you append where you want to or you use the "wrap" plugin http://api.jquery.com/wrap/
Using pure HTML
$(".error").html("<div class='beforeContent'>" + $(".error").html() + "</div>");
Using wrap (http://api.jquery.com/wrap/)
$(".error").wrap("<div class='beforeAndAfter'></div>");
If you want to show an error div after focus out of an input then you have to create it using html/wrap as Luke said and then you have to append it in ot the dom useing
$('.errorWrap').insertAfter('.focusedElement');
But there are other methods available to insert a new element like append/appendTo e.t.c,
I ended up fixing this problem on my own using jquery to create the div and it's nesting on pageload, the divs are generated with an error class that gives display:none. A custom errorPlacement function nests the error in the correct div. Then I used a custom validator highlight function to remove the class that hides the element. Then I used the unhighlight function to re-add the class to re-hide the div.
$(function() {
//Generate the elements and assign attributes
var errorWrap = document.createElement('div');
$(errorWrap).addClass('errorWrap hideError');
var errorTop = document.createElement('div');
$(errorTop).addClass('errorTop');
var topSpan = document.createElement('span');
var errorContent = document.createElement('div');
$(errorContent).addClass('errorContent');
var errorBottom = document.createElement('div');
$(errorBottom).addClass('errorBottom');
var bottomSpan = document.createElement('span');
//Place the elements directly after each dd element
$("dl > dd").append(errorWrap);
$("div.errorWrap").append(errorTop)
.append(errorContent)
.append(errorBottom);
$("div.errorTop").append(topSpan);
$("div.errorBottom").append(bottomSpan);
//Add custom validator defaults
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).nextAll('.errorWrap').children('.errorContent').append(error);
},
highlight: function(element) {
$(element).nextAll('.errorWrap').removeClass('hideError');
},
unhighlight: function(element) {
$(element).nextAll('.errorWrap').addClass('hideError');
}
});
}
Although I'm sure this could have been done more shorthand, I really like this technique because I didn't have to update any of my pages that contained forms to get it to work. All of the nested divs are dynamically created by javascript, so I can include a global file to any page with forms and it will just work. Thanks for all who offered suggestions.

How can I strip down JavaScript code while building HTML?

I am trying to parse some HTML to find images within it.
For example, I created a dynamic div and parsed the tags like this:
var tmpDiv = document.createElement("DIV");
tmpDiv.innerHTML = html;
The HTML should be script-less however there are exceptions, one code segment had the following code under an image tag:
<img src=\"path" onload=\"NcodeImageResizer.createOn(this);\" />
By creating a temp div the "onload" function invoked itself and it created a JavaScript error.
Is there anyway to tell the browser to ignore JavaScript code while building the HTML element?
Edit:
I forgot to mention that later on I'd like to display this HTML inside a div in my document so I'm looking for a way to ignore script and not use string manipulations.
Thanks!
One way of doing this is to loop through the children of the div and remove the event handlers you wish.
Consider the following:
We have a variable containing some HTML which in turn has an onload event handler attached inline:
var html = "<img src=\"http://www.puppiesden.com/pics/1/doberman-puppy5.jpg\"
alt=\"\" onload=\"alert('hello')\" />"
One we create a container to put this HTML into, we can loop through the children and remove the relevant event handlers:
var newDiv = document.createElement("div");
$(newDiv).html(html);
$(newDiv).children().each(function(){this.onload = null});
Here's a working example: http://jsfiddle.net/XWrP3/
UPDATE
The OP is asking about removing other events at the same time. As far as I know there's no way to remove all events in an automatic way however you can simply set each one to null as required:
$(newDiv).children().each(function(){
this.onload = null;
this.onchange = null;
this.onclick = null;
});
You can do it really easily with jquery like this:
EDIT:
html
<div id="content" style="display:none">
<!-- dynamic -->
</div>
js
$("#content").append(
$(html_string).find('img').each(function(){
$(this).removeAttr("onload");
console.log($(this).attr("src"));
})
);

Categories

Resources