Creating HTML element via javascript not working - javascript

I'm currently a newbie to javascript just started learning on how to create new DOM element using the javascript function document.createElement(). The problem is that I'm getting really confused by all these function.The code be low is what I'm trying to create
I'm getting confused on how to append these element to the element having the id "date". Here is what i've done so far
function createElements(){
//creating <div class="divider"></div>
var div = document.createElement('div');
var attributeDivider= document.createAttribute('class');
attributeDivider.value="divider";
div.setAttributeNode(attributeDivider);
//creating <div class="section"></div>
var div2 = document.createElement('div');
var attributeSection = document.createAttribute('class');
attributeSection.value ="section";
div2.setAttributeNode(attributeSection);
//creating h5
var h5 = document.createElement('h5');
var attributeH5 = document.createAttribute('id');
attributeH5.value ="test";
// creating stuff
var stuff = document.createElement('Stuff');
// creating date
var date = document.getElementById("date");
date.appendChild(h5);
}
<!--This_is_where_I_need_to_append the created elements-->
<p id="date">Date Created</p>
<!--The elements that I need to create-->
<div class="divider"></div>
<div class="section">
<h5>Section 1</h5>
<p>Stuff</p>
</div>
Could someone help me ?

You were creating the elements, however, you were not adding them to the HTML.
Try following
function createElements() {
//creating <div class="divider"></div>
var div = document.createElement('div');
var attributeDivider = document.createAttribute('class');
attributeDivider.value = "divider";
div.setAttributeNode(attributeDivider);
//creating <div class="section"></div>
var div2 = document.createElement('div');
var attributeSection = document.createAttribute('class');
attributeSection.value = "section";
div2.setAttributeNode(attributeSection);
// Appending section div to divider div
div.appendChild(div2);
//creating h5
var h5 = document.createElement('h5');
// Adding content
h5.textContent = "Section 1";
// Appending h5 to section div
div2.appendChild(h5);
// creating stuff
var stuff = document.createElement('Stuff');
// Adding content
stuff.textContent = "Stuff";
// Appending stuff element to section div
div2.appendChild(stuff);
// Getting date element
var date = document.getElementById("date");
// Appending the structure created above
date.appendChild(div);
}
createElements();
<p id="date">Date Created</p>

Related

How to create HTML tags (with content) on the fly with JavaScript?

I am trying to convert this HTML code to be generated by Javascript on the fly for live data.
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
Ive found a few methods like: appendChild, getElementById, innerHTML and so on. Here is what I've tried so far. I can't seem to get the data to show up.
stringy = data2.Items[0].groupName.values[i];
var para = document.createElement("div");
var node = document.createTextNode(stringy);
para.appendChild(node);
var element = document.getElementById("parental");
element.appendChild(para);
//create div and give it a class
para.setAttribute('class', 'dropbtn');
var div = document.createElement("div");
div.setAttribute('class', 'dropdown-content');
para.parentNode.insertBefore(div, para.nextSibling);
//create link tags and give them text
var alinky = document.createElement("a");
alinky.setAttribute('id', 'linky');
document.getElementById('linky').innerHTML = "linky poo"
div.appendChild(alinky);
Hopefully someone could fill in the blanks on getting this HTML code to be reproduced with javascript. Thanks in advance!
EDIT:
I am trying to create a dropdown menu like this:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover
However, I am trying to create multiple dropdown menus, that dynamically change in quantity based on a query to DynamoDB (AWS). therefore I am using javascript to create the html tags.
The problem is that the scope of the query function does not allow me to see the data outside of the query function, or even inject data into it.
For example, if I try to get a button description from the query, and write to it descriptionArray[0] = data2.Items[0].description; so that I can append the button to the dropdown div, it doesn't know which iteration I'm on in the for loop due to scope. In this example, descriptionArray[0] will work, but descriptionArray[i] will not work because the for loop is outside the query.
Here is the entire logic:
//group data
var length = data2.Items[0].groupName.values.length;
// create elements
const dpdown1 = document.createElement('div');
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
console.log(dpdown1);
var button = new Array();
var dpdown2 = new Array();
var membersArray = new Array();
var descriptionArray = new Array();
var linksArray = new Array();
var stringy = new Array;
//list groups
for(i = 0; i<length; i++){
// create button, set button attribs
button[i] = document.createElement('button');
button[i].setAttribute('class','dropbtn');
//create dropdown div, set attributes
dpdown2[i] = document.createElement('div');
dpdown2[i].setAttribute('class', 'dropdown-content');
//list of group names
stringy[i] = data2.Items[0].groupName.values[i];
var stringyy = stringy[i];
var desc;
//query group members and description
var docClient1 = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var identityId = AWS.config.credentials.identityId;
var paramsyy = {
ExpressionAttributeValues: {
":v1": stringyy
},
KeyConditionExpression: "groupName = :v1",
TableName: "group"
};
docClient1.query(paramsyy, function(err, data2) {
if (err) {
console.error(err);
}else{
descriptionArray[0] = data2.Items[0].description;
//traverse members
for(k = 0; k<data2.Items[0].members.values.length; k++){
// create dropdown links of members
membersArray[k] = data2.Items[0].members.values[k];
linksArray[k] = document.createElement('a');
linksArray[k].setAttribute('href', '#')
linksArray[k].innerText = membersArray[k];
// nest into dpdown2 div, set dpdown2 attribs
dpdown2[0].appendChild(linksArray[k]);
}
}
});
button[i].innerText = stringyy + ": " + descriptionArray[0];
// nest into dpdown1
dpdown1.appendChild(button[i]);
dpdown1.appendChild(dpdown2[i]);
}
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
if I use the I from the first for loop inside the query function, it will give me undefined results.
here's how you can do it with vanilla JavaScipt, there are multiple ways to do it, but this way only uses 4 methods: createElement, setAttribute, appendChild, and getElementById, and directly sets 1 property: innerText.
// create elements
const dpdown1 = document.createElement('div');
const button = document.createElement('button');
const dpdown2 = document.createElement('div');
const link1 = document.createElement('a');
const link2 = document.createElement('a');
const link3 = document.createElement('a');
// set link attribs
link1.setAttribute('href', '#')
link1.innerText = 'Link 1';
link2.setAttribute('href', '#')
link2.innerText = 'Link 2';
link3.setAttribute('href', '#')
link3.innerText = 'Link 3';
// nest into dpdown2, set dpdown2 attribs
dpdown2.appendChild(link1);
dpdown2.appendChild(link2);
dpdown2.appendChild(link3);
dpdown2.setAttribute('class', 'dropdown-content');
// set button attribs
button.setAttribute('class','dropbtn');
button.innerText = "Dropdown"
// nest into dpdown1
dpdown1.appendChild(button);
dpdown1.appendChild(dpdown2);
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
<div id="target"></div>
You will to append it to something, in this example it's <div id="target"></div> but it could be something else.
Happy coding!
Mainly you are just doing things out of order.
Create the .dropdown <div> with its class.
Complete the .dropbtn <button> with its class and text.
Add the button to the div.
Create the .dropdown-content <div>.
Complete each link with its href attribute and text.
Add each link to the .dropdown-content <div>.
Add the .dropdown-content div to the .dropdown <div>.
Find the parent element in the document.
Append the whole complete .dropdown <div> to the document.
var para = document.createElement("div"); //make .dropdown div
para.setAttribute('class', 'dropdown'); //add .dropdown class to div
var button = document.createElement("button"); //create button
button.setAttribute('class', 'dropbtn'); //add .dropbtn class to button
var node = document.createTextNode('Dropdown'); //create button text
button.appendChild(node); //add text to button
para.appendChild(button); //add button to .dropdown div
var div = document.createElement("div"); //create .dropdown-content div
div.setAttribute('class', 'dropdown-content'); //add .dropdown-content class to div
//repeat for all necessary links
var alinky = document.createElement("a"); //creat link
alinky.setAttribute('href', '#'); //set link href attribute
var alinkyText = document.createTextNode("Link 1"); //create text for link
alinky.appendChild(alinkyText); //add text to link
div.appendChild(alinky); //add link to dropdown div
para.appendChild(div); //add .dropdown-content div to .dropdown div
var element = document.getElementById("parental"); //find parent element
element.parentNode.insertBefore(para, element.nextSibling); //add .dropdown div to the bottom of the parent element
<div id="parental">
</div>

why is the insertBefore showing error

I intend to create a new Div element via javascript, but i am having problem appending my code to the DOM
<div id="container">
<div id="content"></div>
</div>
<script>
var container = document.getElementById('container');
function divCreate() {
var newDiv = document.createElement('div');
var newContent = document.createTextNode('Hello this is
div via javascript!');
newDiv.appendChild(newContent);
var currentDiv = document.getElementById('content');
document.body.container.insertBefore(newDiv, currentDiv);
}
divCreate();
</script>
my actual intention was to insert the new div before the content inside the container. I do understand the DOM as a tree of objects and hierarchy too.I thought that i could navigate the tree via this hierarchy . that is from document--->body----->container.
It did worked on the container, but not the content div. Could someone please tell what I am missing here?
I did try to append the newDiv to the DOM before the content, but I was unable. I was able to append it to the container DIV which is a parent of the content Div. my main concern is why ami unable to append it before the content using the insert before method.
I thought that i could navigate the tree via this hierarchy . that is from document--->body----->container.
You can't.
Use document.getElementById() to get an element by its ID.
try this
<div id="container">
<div id="content">
</div>
</div>
<script>
var container = document.getElementById('container');
function divCreate() {
var newDiv = document.createElement('div');
var newContent = document.createTextNode('Hello ....');
newDiv.appendChild(newContent);
var currentDiv = document.getElementById('content');
document.body.container.insertBefore(newDiv,currentDiv}
divCreate();
</script>
<div id="container">
<div id="content">
</div> </div>
<script>
var container = document.getElementById('container');
function divCreate() {
var newDiv = document.createElement('div');
var newContent = document.createTextNode('Hello this is a div is added via javascript');
newDiv.appendChild(newContent);
var currentDiv = document.getElementById('content');
container.insertBefore(newDiv, currentDiv);
}
divCreate();
</script>

Pass 'div' element as parameter to JavaScript function

I need to create, decorate and append child 'divs' to existing. For example, after the appendChildren is executed, following divs
<div id="a">
<div id="b">
</div>
</div>
should take the following form (assuming decorateDiv adds text "This is new div" inside new div)
<div id="a">
<div id="b">
<div>"This is new div"</div>
</div>
<div>"This is new div"</div>
</div>
Here is my code
function appendChildren() {
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var x = document.getElementByTagName("div");
var t = document.createTextNode("This is new div");
x.appendChild(t);
}
I am completely new to JavaSpript. What am I doing wrong? Please help me to fix bugs
You're not using the parameter div and the decorateDiv should look like this:
function decorateDiv(div) {
//div is the object element
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
The parameter 'div' that you are passing to function 'decorateDiv' has nowhere been used.
You can change your decorateDiv function like as below:
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
Hope this helps!!
"allDivs" variable get update when to appendChild to any div because to stores array of elements of "div" TagName.
So, use class for fetching divs.
<div id="a" class="test">
A
<div id="b" class="test">
B
</div>
</div>
Here is user script:
function appendChildren() {
var allDivs = document.getElementsByClassName("test");
for (var i = 0 ; i < allDivs.length ; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
appendChildren();
And also you are not using parameter passed to decorative function.
This will work. Try this..

How do you use Javascript to add or remove HTML/CSS code?

If I have a bunch of HTML code, similar to the following:
<div id='test0div'>
<p id='test0'></p>
</div>
How do I use JavaScript to add or remove more of those - i.e.
<div id='test1div'>
<p id='test1'></p>
</div>
<div id='test2div'>
<p id='test2'></p>
</div>
...etc.?
var container = document.createElement("div");
for(var i=0; i<5; i++) { // change i <5 as per your data source
var div = document.createElement("div");
var p = document.createElement("p");
p.id = "test"+i;
div.id = "test"+i+"div";
div.appendChild(p);
container.appendChild(div); // you can event append to particular id or body
}
// document.getElementById("divId").appendChild(container);
container, will have all the divs & p as you wish
This will give you the output you want. Just change the number of times the loop will execute based on your wish.
To remove you could use
$('#id').remove();
To add you could use
$("<div id='new'></div>").appendTo('#id');

How to correctly iterate over list items to create html content?

Desired Behaviour
On clicking a button, for each li which contains an image, a function creates and appends divs to a parent div.
The markup for each instance of an li should look like this after running the function:
<div class="recipe_container">
<div class="recipe_meta">
<div class="recipe_left_col">
<div class="recipe_right_col">
Current Behaviour
In the demonstration, which should create two instances of <div class="recipe_container">, the first iteration of the function is producing replica nested divs. The second iteration is creating the correct markup.
It is looking like this:
<div class="recipe_container">
<div class="recipe_meta">
<div class="recipe_left_col">
<div class="recipe_right_col">
<div class="recipe_meta"> <!--bad-->
<div class="recipe_left_col"> <!--bad-->
<div class="recipe_right_col"> <!--bad-->
<div class="recipe_container">
<div class="recipe_meta">
<div class="recipe_left_col">
<div class="recipe_right_col">
Notes
I'm new to creating divs with javascript, so am sure my approach to constructing the function is overly verbose, but i'm just trying to understand the logic first and will make the function more succinct when I have a better understanding of how it operates.
Demonstration
http://jsfiddle.net/rwone/nSws2/
Script
It basically follows the format of:
create element
apply attributes
append it to necessary parent div
Like I said, there must be a more succinct way, but this is all I know at the moment.
function createContent(day, meal, img_src, time) {
// create recipe container
var r_container = document.createElement("div");
r_container.className = "recipe_container";
// append recipe container
$("#right_shopping_list_creator").append(r_container);
// create recipe meta
var r_meta = document.createElement("div");
r_meta.className = "recipe_meta";
// append recipe meta
$(".recipe_container").append(r_meta);
// create day paragraph
var r_day = document.createElement("p");
r_day.className = "day";
r_day.innerHTML = day;
// create meal paragraph
var r_meal = document.createElement("p");
r_meal.className = "meal";
r_meal.innerHTML = meal;
// append day and meal
$(".recipe_meta").append(r_day, r_meal);
// create recipe left col
var r_left_col = document.createElement("div");
r_left_col.className = "recipe_left_col";
// append recipe left col
$(".recipe_container").append(r_left_col);
// create image
var r_image = document.createElement("img");
r_image.src = img_src;
// append image
$(".recipe_left_col").append(r_image);
// create recipe right col
var r_right_col = document.createElement("div");
r_right_col.className = "recipe_right_col";
// append recipe right col
$(".recipe_container").append(r_right_col);
// create time paragraph
var r_time = document.createElement("p");
r_time.innerHTML = time;
// create ingredients paragraph
var r_ingredients = document.createElement("p");
r_ingredients.innerHTML = "ingredients";
// append time and ingredients
$(".recipe_right_col").append(r_time, r_ingredients);
// create ul
var r_ul = document.createElement("ul");
// append ul
$(".recipe_right_col").append(r_ul);
// create directions paragraph
var r_directions = document.createElement("p");
r_directions.innerHTML = "directions";
// append directions paragraph
$(".recipe_right_col").append(r_directions);
// create ol
var r_ol = document.createElement("ol");
// append ol
$(".recipe_right_col").append(r_ol);
}
$(document).on("click", "button", function() {
var day_name = $(".day_name");
// for each day
$(day_name).each(function(x, y) {
var lis = $(y).find("li");
// for each li (meal)
$(lis).each(function(i, data) {
// if li contains an image (meal)
if ($(data).find('img').length) {
var img_filename = $(data).find("img").attr("src");
var testday = "monday";
var testmeal = "breakfast";
var testtime = "6:00am";
createContent(testday, testmeal, img_filename, testtime);
}
});
});
});
You need to use the newly created element reference to add new elements to it, instead of running a selector like
function createContent(day, meal, img_src, time) {
// create recipe container
var $rc = $('<div />', {
'class': 'recipe_container'
}).appendTo('#right_shopping_list_creator')
// create recipe meta
var $rmeta = $('<div />', {
'class': 'recipe_meta'
}).appendTo($rc)
// create day paragraph
var $rday = $('<p />', {
'class': 'day',
html: day
}).appendTo($rmeta)
// create meal paragraph
var $rday = $('<p />', {
'class': 'meal',
html: meal
}).appendTo($rmeta)
// create recipe left col
var $rlc = $('<div />', {
'class': 'recipe_left_col'
}).appendTo($rc)
// create image
$('<img />', {
src: img_src
}).appendTo($rlc)
// create recipe right col
var $rrc = $('<div />', {
'class': 'recipe_right_col'
}).appendTo($rc)
// create time paragraph
$('<p />', {
html: time
}).appendTo($rrc)
// create ingredients paragraph
$('<p />', {
html: 'ingredients'
}).appendTo($rrc)
// create ul
var $rrcul = $('<ul />').appendTo($rrc)
// create directions paragraph
$('<p />', {
html: 'directions'
}).appendTo($rrc)
// create ol
var $rrcol = $('<ul />').appendTo($rrc)
}
Demo: Fiddle

Categories