Generate HTML with JavaScript not working? - javascript

I'm quite new to JavaScript so I don't understand what's not working.
The Code:
var postCount = 0;
function generatePost(title, time, text) {
var div = document.createElement("div");
div.className = "content";
div.id = "post_" + postCount;
document.getElementById("postcontainer").appendChild(div);
var h3 = document.createElement("h3");
div.id = "post_h3_" + postCount;
h3.innerHTML = title;
document.getElementById("post_" + postCount).appendChild(div);
var span = document.createElement("span");
document.getElementById("post_h3_" + postCount).appendChild(div);
span.innerHTML = time;
var paragraphs[] = text.split("||");
for (var p : paragraphs[] {
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
postCount++;
}
function loadPosts() {
generatePost("Testing Title", "I don't know", "This is || a paragraph");
}
I included it with:
<body onload="loadPosts()">
In the end, nothing shows up. Not even in the Inspector in my Browser. Is my Code even run? Did I forget an essential doStuffNow()?
Second: If I add a class to a div with JavaScript, do the CSS-Rules in the style.css append to it?

To answer the second part of your question, yes, the CSS styling that applies to a class will be added to an object that you add the same class to.

You have errors in your code. What editor do you use? You can also use browser console to check for errors in your page.
Check here:
var paragraphs = text.split("||");
for (var p in paragraphs) {
/*
*
* Where do you use your var p?
*
*/
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
Why don't you try with jQuery?

Related

How to get the elements class name from a dynamically created element?

I started creating some minor code within my site, and i wanted to do some dynamic creation, so some span tags are created using a javaScript for loop.
In the same code, but a different loop i want to add an Event Listener to the tags.The error i get is the element created is non existent, and i have a few ideas why it's not working, but searching the Web and Stack Overflow gave me no answers.
I've considered putting both for loops into a function and calling that function in a similar fashion jquery works with it's document ready function. But i don't think that will fix the issue
var country = ["is_AmericaN", "is_Europe",
"is_Africa","is_AmericaS","is_Asia","is_Australia"];
var spanInto = document.getElementById("spanSelect");
for(i=0; i<6; i++)
{
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
The code above creates the elements, the code below tries to call them
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
countryClass[i].addEventListener("click", function(){
var hrDisplay = document.getElementById("selectiveDisplay");
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
},false);
}
I expect the working code to, once clicked on any span tag, set the display of the hr tag to block or flex. I dont want to create 5-6 span tags manually, it has to be a dynamic creation.
You are missing the position of the adding class
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
Here you are assigning the class after appending it into span, that is wrong you need to assign class before.
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
doucment is document and document.countryClass should be countryClass as you already have the instance of the element
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("SPAN");
spanMake.textContent = country[i];
spanMake.className += "spanLanguage" + " " + country[i];
spanInto.appendChild(spanMake);
}
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function() {
var hrDisplay = this;
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
}, false);
}
.noDisplay {
display: none;
}
<span id="spanSelect"></span>
<br/>
//click on any of them to replace the class
There are multiple points to be corrected:
There was a type "doucment" in your code.Use "document" instead.
Created elements didn't have any text on it, how will you call click
on element when it is not visible in DOM.
Events are attached to anchors/button not span.
Not sure what you are trying to do by attaching events.
below is the code snippet which works for you when you try to add events on dynamic created elements.Let me know if you need further help
function temp() {
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("a");
spanMake.innerHTML = country[i];
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
}
function attachEvent() {
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function(event) {
console.log("I am called" + event.target);
//var hrDisplay = document.getElementById("selectiveDisplay");
//hrDisplay.removeAttribute("id");
//hrDisplay.className = "noDisplay";
}, false);
}
}
a {
padding: 20px;
}
<body>
<div id="spanSelect"></div>
<div id="selectiveDisplay"> </div>
<button onclick="temp()"> Call Me </button>
<button onclick="attachEvent()"> Attach Event </button>
</body>

Javascript CreateElement(br)

I am trying to create a score keeper display.
I want to keep track of the score using html and javascript. I have everything figured out I think but I can't figure out why the line doesn't break here.
Relevant code:
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br);
scorechart.appendChild(tot);
}
(For a full view: https://hastebin.com/osuduluvaj.js)
It breaks for everything but the "------" part: https://media.discordapp.net/attachments/240883852350980096/497957073481629696/sAAAAASUVORK5CYII.png
(I cant upload images yet as a new member)
Thank you :)
document.createElement() creates a single element, which you can only append to the DOM once. If you want to reuse the <br> element you created, you need to clone it and you can insert the cloned copy into the DOM. See: Node.cloneNode().
var score = [];
var scoreadd_button = document.querySelector('#scoreadd-button');
var scoreadd_input = document.querySelector('#scoreadd-input');
let sc1 = 0;
let sc2 = 0;
var scorechart = document.querySelector('.scores');
function totalScores() {
var i;
var sum = 0;
for (i = 0; i < score.length; i++) {
sum += score[i];
}
return sum;
}
function newScore(amm) {
score.push(amm);
if (!score[1]) {
var nc = document.createTextNode(amm)
} else {
var nc = document.createTextNode(" + " + amm);
}
if (sc1 == 0) {
sc1 = amm;
} else {
sc2 = amm;
}
if (sc2 != 0) {
var tot = document.createTextNode("= " + totalScores());
sc1 = amm;
sc2 = 0;
}
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(nc);
if (tot) {
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(nes);
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(tot);
}
}
scoreadd_button.addEventListener('click', function() {
var amm = scoreadd_input.value;
newScore(parseInt(amm, 10));
});
<button id="scoreadd-button">button</button>
<input type="text" id="scoreadd-input" />
<div class="scores"></div>
Okay so I fixed the issue by instead of using a variable just creating the element in the statement.
var nes = document.createTextNode("---------");
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nes);
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(tot);
}
Thank you :)
You just need to defined unique variables for each new created element on javascript, otherwise they will counted as one.
This code should works
var scorechart = document.querySelector('.scores');
var br = document.createElement("br");
var br2 = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br2);
<span class="scores">
text before
</span>
after text

Create element until condition is true

I want to create elements inside another element until condition is true.
I have tried this code but it's not working.
// calculate span size and it's parent
var homeHeight = $(".home").height();
var homeWidth = $(".home").width();
var homeSize = (homeHeight + homeWidth) * 2;
var spanHeight = $(".back-animation span").height();
var spanWidth = $(".back-animation span").width();
var spanSize = (spanHeight + spanWidth) * 2;
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
};
createSpan();
Note: It's combined with JQuery and I recieve no errors in console.
Note 2: I tried for loop like the bottom but it's not working either.
for (spanSize; spanSize <= homeSize; spanSize = spanSize + spanSize) {
$(".animation-hide-overflow").append(span);
}
EDIT:
Thanks for mentioning, I forgot to call createSpan function! now it's working but it create span just once. Any solutions?
jsfiddle for better demonstration:
http://jsfiddle.net/pooria_h/vqmgmyj0/1/
(It should keep creating span elements until it fills up parent element.)
The problem was this section
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}
If you pay more attention you can see I've created span variable outside of the loop, So this is what happens: Loop works correctly and it increases spanSize variable until it equals to homeSize variable which is bigger in the start point but the big problem is there isn't a element creation! span element is created before the loop.
So this is the correct way:
// create span elements to fill it's parent.
var createSpan = function() {
while (spanSize <= homeSize) {
var span = document.createElement("span");
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}

Declare JScript variables by array and for loop

There is some part of my code that gives me headaches. I've missed something. I want to create, declare variables by array but it won't work. It works fine when I declare them manually (like am1=1; am2=2;...). But the problem is when I try the for loop and to create variables that way.
There is the FIDDLE of my problem
myhtml.html
1.Question:<br/>
<textarea name="question11" ></textarea><br/><div id="inner1"></div><button type="button" onClick="addmore1();">Add more</button>
<br/><br/>
2.Question:<br/>
<textarea name="question21" ></textarea><br/><div id="inner2"></div><button type="button" onClick="addmore2();">Add more</button>
myscript.js
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am1++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am1;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am2++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am2;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
Here is the fiddle with the fix for your problem.
If you look at the developer console (F12 in most browsers), you can see the error: am1 and am2 are undefined.
I guess what you meant to do is to refer to am[1] instead of am1. Althought the code is working after that change, there is a lot of room for improvement: you could reuse more code by having only one addmore function, etc . e.g.:
function addmore(index) {
am[index]++;
var textarea = document.createElement("textarea");
textarea.name = "question" + index + am[index];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
if you are declaring them by array, why aren't you using them by array?
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am[1]++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[1];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am[2]++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[2];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
or am I missing something?
You must use .push() to add values to an array.
var am = [];
for(i=1; i<3; i++){
am.push(1);
}
Sorry if I didn't answer your question completely.

javascript appenchild

for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}

Categories