For a little project I am doing I am interested in creating a small modal form using JavaScripts createElement function. I have the HTML laid out and have actually built the code in JS but sadly cannot seem to get everything to add correctly.
The HTML is supposed to look like this:
<div id="qtModal">
<div id="qtHead">
<span id="qtHeading">Quick Tools</span>
<span id="qtClose">X</span>
</div>
<table id="qtWrapper" border="1">
<tr>
<td id="qtRail">
<ul>
<li><a class="qtLink" href="#">Delete</a></li>
</ul>
</td>
</tr>
</table>
</div>
The JavaScript I set up to make this and append it to the body is as follows:
var qtModal = document.createElement("div");
qtModal.setAttribute("id", "qtModal");
var qtHead = document.createElement("qtHead");
qtHead.setAttribute("id", "qtHead");
var qtHeading = document.createElement("span");
qtHeading.setAttribute("id", "qtHeading");
qtHeading.textContent = "Quick Tools";
var qtClose = document.createElement("span");
qtClose.setAttribute("id", "qtClose");
qtClose.textContent = "X";
var qtWrapper = document.createElement("table");
qtWrapper.setAttribute("id", "qtWrapper");
qtWrapper.setAttribute("border", "1");
var qtTr = document.createElement("tr");
var qtRail = document.createElement("td");
qtRail.setAttribute("id", "qtRail");
var qtUl = document.createElement("ul");
var qtLi1 = document.createElement("li");
var qtA1 = document.createElement("a");
qtA1.setAttribute("class", "qtLink");
qtA1.setAttribute("href", "#");
//We want to build the modal head right here
qtHead = qtHead.appendChild(qtHeading);
qtHead = qtHead.appendChild(qtClose);
qtModal = qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1 = qtLi1.appendChild(qtA1);
qtUl = qtUl.appendChild(qtLi1);
qtRail = qtRail.appendChild(qtUl);
qtTr = qtTr.appendChild(qtUl);
qtWrapper = qtWrapper.appendChild(qtTr);
qtModal = qtModal.appendChild(qtWrapper); //Add to modal
$("body").append(qtModal); //Add to body
My logic is the we first want to add the heading and the close button to the head element by appending them one at a time. I will then append the head to the actual modal element. Next up I will start building the table from the innermost element (a) up to the outermost element (form) then append those to the Modal. When I use the code above only the innermost element (a) gets appended to the body. I would appreciate it if someone could help either point out what I am doing wrong (I might be misusing createElement or appendChild) or how I could fix it to generate the proper HTML structure listed above.
This is basically fine - the issue is that you're overwriting your existing nodes with your appended nodes. Here's why that's happening.
The appendChild(...) method returns the DOM element that was just appended. So, when you call qtHead = qtHead.appendChild(qtHeading), then
qtHeading gets appended to qtHead
qtHead.appendChild(qtHeading) returns a reference to qtHeading
qtHead gets overwritten with qtHeading
So, to fix this, just take this:
qtHead = qtHead.appendChild(qtHeading);
qtHead = qtHead.appendChild(qtClose);
qtModal = qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1 = qtLi1.appendChild(qtA1);
qtUl = qtUl.appendChild(qtLi1);
qtRail = qtRail.appendChild(qtUl);
qtTr = qtTr.appendChild(qtUl);
qtWrapper = qtWrapper.appendChild(qtTr);
qtModal = qtModal.appendChild(qtWrapper); //Add to modal
and rewrite it as this:
qtHead.appendChild(qtHeading);
qtHead.appendChild(qtClose);
qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1.appendChild(qtA1);
qtUl.appendChild(qtLi1);
qtRail.appendChild(qtUl);
qtTr.appendChild(qtUl);
qtWrapper.appendChild(qtTr);
qtModal.appendChild(qtWrapper); //Add to modal
Related
The following is the HTML that does what I want. It displays category: and beneath a value that I send in JavaScript.
<div id="category-order-id" class="additional-order-info">
<!-- <span class="additional-order-info-grey">category:</span>
Clothes -->
</div>
And here is my JavaScript
let orderCategory = document.getElementById("category-order-id");
orderCategory.textContent = `${order.category}`;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(categorySpan);
What this code does, it that it first displays Clothes value that I send with JavaScript and beneath it display category.
Why I am creating a span element here is because if I set textContent of orderCategory it wil not display the span at all.
What am I doing wrong here?
textContent property replaces all the content in the element. If you want to keep order.category and "category:" as content, you need to use the appendChild function:
let orderCategory = document.getElementById("category-order-id");
const catTextContent = document.createElement("span");
catTextContent.textContent = order.category;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(catTextContent);
orderCategory.appendChild(categorySpan);
I have a list with people's data inside it has a li element with 3 p tags inside, one for name, one for address and one for email.
I filled this list manually but due to some changes to my code I had to rewrite this so the html would be made with javascript.
My code looked like this
<p class="adres">#logopedist.Adres</p>
<p class="email">#logopedist.Email</p>
<p class="mobiel">#logopedist.Mobiel</p>
I rewrote this to build the html using javascript. This looks something like this.
var li = document.createElement('li');
li.className = "lijst";
li.id = "lijst";
li.onclick = "ficheVullen(this)";
p.className = "naam";
p.innerHTML = objLogos.Naam[i];
li.appendChild(p);
p.className = "adres";
p.innerHTML = objLogos.Adres[i];
li.appendChild(p);
var p = document.createElement('p');
p.className = "mobiel";
p.innerHTML = objLogos.Mobiel[i];
li.appendChild(p);
My list generates properly. But in my old code I had this at the start of the list.
<li class="lijst" onclick="ficheVullen(this)">
Whenever you would click an li element it would fill a div with the info from the p tags inside that li, so it would fill the div with name, address, mobile,etc
I cannot seem to get this function to work anymore. It only works on the very first LI element and only works for the name. Even though my code is the same and I append classes to the tags like it had in my old code.
The function looks like this:
function ficheVullen() {
FicheNaam = document.getElementById("FicheNaam");
FicheAdres = document.getElementById("FicheAdres");
FicheGSM = document.getElementById("FicheGSM");
FicheNaam.innerHTML = this.querySelector('.naam').textContent;
FicheGSM.innerHTML = this.querySelector('.mobiel').textContent;
FicheAdres.innerHTML = this.querySelector('.adres').textContent;
I get this error now. Cannot read property 'textContent' of null
I call this function here:
window.onload = function() {
changePage(1);
document.getElementById("lijst").addEventListener("click", ficheVullen);
};
The changepage function is part of my pagination where I use javascript to build the list.
When I move the eventlistener out of this I get this error: Cannot read property 'addEventListener' of null.
I hope this gives enough context
You have to use setAttribute to set id.
elm.setAttribute("id", "uniqueId");
Your case : li.setAttribute("id", "lijst")
li.id = "lijst"; will add "id" to object not as attribute
const parent = document.getElementById("container")
let elm = document.createElement("p")
elm.setAttribute("id", "pElm")
elm.innerText = "p tag"
parent.append(elm)
document.getElementById("pElm").style.background = "red"
<div id="container"></div>
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>
<div id="wpq2">
<div class="subClass">
<a id="linkTO" class="subClass">New Item</a>
or
<a class="subClass">edit</a>
this list
</div>
</div>
i want to hide all the thing except
<a id="linkTO" class="subClass">New Item</a>
I do not have access to html ,
i have to use javascript
i tried somthing
var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';
Using javascript no idea how to do
Please suggest
Try this instead:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get all the a elements
var subs = innerDiv.getElementsByClassName('subClass');
//This will hide all matching elements except the first one
for(var i = 1; i < subs.length; i++){
var a = subs[i];
a.style.display = 'none';
}
Here is a working example
EDIT: The above will only hide the a element, as your text elements are not contained within specific elements then it becomes more tricky. If you are happy to effectively "delete" the HTML you don't want then you can do the following:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get the HTML for the a element to keep
var a = innerDiv.getElementsByClassName('subClass')[0].outerHTML;
//replace the HTML contents of the inner DIV with the element to keep
innerDiv.innerHTML = a;
Here is an example
insert new html if you don't need the rest
document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';
var parentID = document.getElementById('wpq2');
var innerDiv = parentID.getElementsByClassName('subClass')[0];
var subs = innerDiv.getElementsByClassName('subClass');
subs.forEach(function (sub) { sub.style.display = 'none'; });
document.getElementById("linkTO").style.display = 'block';
I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element