Dynamically creating HTML elements using Javascript? - javascript

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.
function createMyElements(id1,id2,id3){
//create anchor with id1
//create div with id 2
//create xyz with id3
//now return the html code of above created just now
}
How can I do this?

[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found # the bottom of the snippet.
// The classic createElement
// -------------------------
// create a paragraph element using document.createElement
const elem = document.createElement(`p`);
elem.id = `myBrandnewDiv1`;
// put in some text
elem.appendChild(document.createTextNode(`My brand new div #1`));
// append some html (for demo, preferrably don't use innerHTML)
elem.innerHTML += ` => created using
<code>document.createElement</code>`;
// append a new paragraph within #myBrandNewDiv1
const nested = elem.appendChild(document.createElement(`p`));
nested.classList.add(`nested`);
// add some text to that
nested.textContent = `I am nested!`;
// the elements are still in memory, now add the
// whole enchillada to the document
document.body.appendChild(elem);
// insertAdjacentHTML
// ------------------
// nest an element within the nested div
nested.insertAdjacentHTML(`afterbegin`,
`<div id="nestedWithin#nested">
This text will appear <i>above</i> the text of
my parent, that being div#nested.
Someone had the nerve to insert me using
<code>insertAdjacentHTML</code>
</div>`);
// Object.assign
// -------------
// Use Object.assign to create an element and
// assign properties/html to it in one go
const newElem = Object.assign(
document.createElement(`div`),
{ id: `myBrandnewDiv2`,
innerHTML: `div#myBrandnewDiv2 signing in.
I was <i>assigned</i> using <code>Object.assign</code>…`});
document.body.appendChild(newElem);
// insertAdjacentElement combined with Object.assign
// -------------------------------------------------
// use the above technique combined with insertAdjacentElement
newElem.insertAdjacentElement(
`beforeend`,
Object.assign(document.createElement(`span`),
{ id: `myBrandnewnested2_nested`,
innerHTML: `<br>Me too! And appended I was
with <code>insertAdjacentElement</code>` })
);
// createDocumentFragment
// ----------------------
// Use a document fragment to create/inject html
const fragment = document.createDocumentFragment();
const mdnLnk = `https://developer.mozilla.org/en-US/` +
`docs/Web/API/Document/createDocumentFragment`;
fragment.appendChild(
Object.assign(
document.createElement(`p`),
{innerHTML: `Regards from <code>createDocumentFragment</code>
(see MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<div id="id2">Hi!</div>
<p id="id3">Hi 2!</p>`,
classList: [`xyz`], } );
const prepareHtml4Reporting = html =>
html.replace(/</g, `<`)
.replace(/\n\s+/g, `\n`)
.replace(/\n\n/g, `\n`);
document.body.insertAdjacentHTML(
`beforeend`,
`<h3>html only</h3><pre>${
prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}
code {
background-color: #eee;
}
.nested {
margin-left: 0.7rem;
max-width: 450px;
padding: 5px;
border: 1px solid #ccc;
}
I have used some of these methods in this library (see /src/DOM.js), with a mechanism for sanitizing html before it is injecting.

Html:
<div id="main"></div>
JavaScript:
var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));
var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));
tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);
The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.
At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)
With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.
Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.

If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.
If you want to create three unrelated elements, you can do:
var anchor = elem("a", {"id":"id1"});
var div = elem("div", {"id":"id2"});
var xyz = elem("div", {"id":"id3"});
Now, you have three elements. If you want to get the HTML of these (as string), simply do:
var html = anchor.outerHTML + div.outerHTML + xyz.outerHTML;
If you want to have these three in an element (say, div), do:
var div = elem("div", null, [
elem("a", {"id":"id1"}),
elem("div", {"id":"id2"}),
elem("div", {"id":"id3"}),
]);
You can get the HTML with div.outerHTML, or you can just append it anywhere you want.
To know more about elem(), visit element.js (GitHub).
I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.

You can construct the html as a string in one variable like
var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on
then you return the variable html
return html;

The better way would be to Import ElementsJS and just reference each element in it.
var root = document.getElementById("root");
var elementdiv = create_element('div',{'class':'divcss'}, root, null);
create_element('h1',{'class':'hellocss'}, elementdiv, "Hello World");
.hellocss {
color : red;
}
.divcss {
background-color : blue;
height: 100px;
position: absolute;
}
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>
For More Details Refer to https://github.com/divyamshu/Elements-JS
Well Documented with Example.

Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).
Let us say, you have html-page as "index.html" (calling index_static.html here).
index_static.html
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1> Hello !!! </h1>
</body>
</html>
You can open this file in the browser, to see the desired output.
Now, lets create a javascript equivalent to this.
Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:
dynamic.js
document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write(" <head>");
document.write(" <title>Test<\/title>");
document.write(" <\/head>");
document.write(" <body>");
document.write(" <h1> Hello !!! <\/h1>");
document.write(" <\/body>");
document.write("<\/html>");
And now, your dynamic version of the static_index.html will be as below:
index_dynamic.html
<script language="JavaScript" src="dynamic.js"></script>
Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).
more info

Related

insertAdjacentHTML then select with dom selector

I want to insert some unknown HTML (contentToInsert) and remove it later at some point.
If I use insertAdjacentHTML, I cannot later say
myDiv.insertAdjacentHTML('afterbegin', contentToInsert);
myDiv.querySelector('contentToInsert') //cannot work of course
because this does not have id or classname.
I cannot wrap it like this (so I have reference to it later):
var content = document.createElement('div');
content.classList.add('my-content-wrap')
content.innerHTML = contentToInsert;
myDiv.insertAdjacentHTML('afterbegin', adContent);//it can be any allowed position, not just afterbegin
Basically I want to remove it later at some point but dont know how to select it. I dont know the position in which this is going to be instered.
Since insertAdjacentHTML only accepts a string you can
Define your content as a string
Use a template/string to add it
Add that string to myDiv.
Then you can target myDiv again with a selector pointed at that element with the my-content-wrap class, and remove it from the DOM.
const myDiv = document.querySelector('#myDiv');
const content = 'Disappears after two seconds';
const html = `<div class="my-content-wrap">${content}</div>`;
myDiv.insertAdjacentHTML('afterbegin', html);
const pickup = myDiv.querySelector('.my-content-wrap');
setTimeout(() => pickup.remove(), 2000);
<div id="myDiv">Original content</div>
You said "I want to insert some unknown HTML (contentToInsert) and remove it later at some point"
I wouldn't use insertAdjacentHTML at all. Here's how you can achieve it:
let myDiv = document.getElementById('myDiv');
let contentToInsert = "<h1>Some html content</h1>";
myDiv.innerHTML = contentToInsert;
This will insert your content into your div. And you can remove it with:
myDiv.innerHTML = "";
in one of the cases...
const
divElm = document.querySelector('#div-elm')
, Insert_1 = '<span>inserted content 1 </span>'
, Insert_2 = '<span>inserted content 2 </span>'
;
divElm.insertAdjacentHTML('afterbegin', Insert_1);
const ref_1 = divElm.firstChild;
divElm.insertAdjacentHTML('afterbegin', Insert_2);
const ref_2 = divElm.firstChild;
ref_1.classList.add('RED')
ref_2.classList.add('BLU')
console.log( '', ref_1, `\n`, ref_2 )
.RED { color: red; }
.BLU { color: blue; }
<div id="div-elm">
blah blah bla..
</div>
many amazing people already answered your question but here's a workaround, if you're only Adding this specific html using js and other content is preadded in html it's always gonna be the first child as you're using afterbegin or else you can do it like others gave you examples.
Sorry can't comment not enough reputation and recently joined

How do I create a new HTML element from JavaScript? [duplicate]

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.
function createMyElements(id1,id2,id3){
//create anchor with id1
//create div with id 2
//create xyz with id3
//now return the html code of above created just now
}
How can I do this?
[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found # the bottom of the snippet.
// The classic createElement
// -------------------------
// create a paragraph element using document.createElement
const elem = document.createElement(`p`);
elem.id = `myBrandnewDiv1`;
// put in some text
elem.appendChild(document.createTextNode(`My brand new div #1`));
// append some html (for demo, preferrably don't use innerHTML)
elem.innerHTML += ` => created using
<code>document.createElement</code>`;
// append a new paragraph within #myBrandNewDiv1
const nested = elem.appendChild(document.createElement(`p`));
nested.classList.add(`nested`);
// add some text to that
nested.textContent = `I am nested!`;
// the elements are still in memory, now add the
// whole enchillada to the document
document.body.appendChild(elem);
// insertAdjacentHTML
// ------------------
// nest an element within the nested div
nested.insertAdjacentHTML(`afterbegin`,
`<div id="nestedWithin#nested">
This text will appear <i>above</i> the text of
my parent, that being div#nested.
Someone had the nerve to insert me using
<code>insertAdjacentHTML</code>
</div>`);
// Object.assign
// -------------
// Use Object.assign to create an element and
// assign properties/html to it in one go
const newElem = Object.assign(
document.createElement(`div`),
{ id: `myBrandnewDiv2`,
innerHTML: `div#myBrandnewDiv2 signing in.
I was <i>assigned</i> using <code>Object.assign</code>…`});
document.body.appendChild(newElem);
// insertAdjacentElement combined with Object.assign
// -------------------------------------------------
// use the above technique combined with insertAdjacentElement
newElem.insertAdjacentElement(
`beforeend`,
Object.assign(document.createElement(`span`),
{ id: `myBrandnewnested2_nested`,
innerHTML: `<br>Me too! And appended I was
with <code>insertAdjacentElement</code>` })
);
// createDocumentFragment
// ----------------------
// Use a document fragment to create/inject html
const fragment = document.createDocumentFragment();
const mdnLnk = `https://developer.mozilla.org/en-US/` +
`docs/Web/API/Document/createDocumentFragment`;
fragment.appendChild(
Object.assign(
document.createElement(`p`),
{innerHTML: `Regards from <code>createDocumentFragment</code>
(see MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<div id="id2">Hi!</div>
<p id="id3">Hi 2!</p>`,
classList: [`xyz`], } );
const prepareHtml4Reporting = html =>
html.replace(/</g, `<`)
.replace(/\n\s+/g, `\n`)
.replace(/\n\n/g, `\n`);
document.body.insertAdjacentHTML(
`beforeend`,
`<h3>html only</h3><pre>${
prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}
code {
background-color: #eee;
}
.nested {
margin-left: 0.7rem;
max-width: 450px;
padding: 5px;
border: 1px solid #ccc;
}
I have used some of these methods in this library (see /src/DOM.js), with a mechanism for sanitizing html before it is injecting.
Html:
<div id="main"></div>
JavaScript:
var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));
var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));
tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);
The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.
At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)
With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.
Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.
If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.
If you want to create three unrelated elements, you can do:
var anchor = elem("a", {"id":"id1"});
var div = elem("div", {"id":"id2"});
var xyz = elem("div", {"id":"id3"});
Now, you have three elements. If you want to get the HTML of these (as string), simply do:
var html = anchor.outerHTML + div.outerHTML + xyz.outerHTML;
If you want to have these three in an element (say, div), do:
var div = elem("div", null, [
elem("a", {"id":"id1"}),
elem("div", {"id":"id2"}),
elem("div", {"id":"id3"}),
]);
You can get the HTML with div.outerHTML, or you can just append it anywhere you want.
To know more about elem(), visit element.js (GitHub).
I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.
You can construct the html as a string in one variable like
var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on
then you return the variable html
return html;
The better way would be to Import ElementsJS and just reference each element in it.
var root = document.getElementById("root");
var elementdiv = create_element('div',{'class':'divcss'}, root, null);
create_element('h1',{'class':'hellocss'}, elementdiv, "Hello World");
.hellocss {
color : red;
}
.divcss {
background-color : blue;
height: 100px;
position: absolute;
}
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>
For More Details Refer to https://github.com/divyamshu/Elements-JS
Well Documented with Example.
Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).
Let us say, you have html-page as "index.html" (calling index_static.html here).
index_static.html
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1> Hello !!! </h1>
</body>
</html>
You can open this file in the browser, to see the desired output.
Now, lets create a javascript equivalent to this.
Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:
dynamic.js
document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write(" <head>");
document.write(" <title>Test<\/title>");
document.write(" <\/head>");
document.write(" <body>");
document.write(" <h1> Hello !!! <\/h1>");
document.write(" <\/body>");
document.write("<\/html>");
And now, your dynamic version of the static_index.html will be as below:
index_dynamic.html
<script language="JavaScript" src="dynamic.js"></script>
Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).
more info

How would I add the information entered in a form onto the page? [duplicate]

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.
function createMyElements(id1,id2,id3){
//create anchor with id1
//create div with id 2
//create xyz with id3
//now return the html code of above created just now
}
How can I do this?
[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found # the bottom of the snippet.
// The classic createElement
// -------------------------
// create a paragraph element using document.createElement
const elem = document.createElement(`p`);
elem.id = `myBrandnewDiv1`;
// put in some text
elem.appendChild(document.createTextNode(`My brand new div #1`));
// append some html (for demo, preferrably don't use innerHTML)
elem.innerHTML += ` => created using
<code>document.createElement</code>`;
// append a new paragraph within #myBrandNewDiv1
const nested = elem.appendChild(document.createElement(`p`));
nested.classList.add(`nested`);
// add some text to that
nested.textContent = `I am nested!`;
// the elements are still in memory, now add the
// whole enchillada to the document
document.body.appendChild(elem);
// insertAdjacentHTML
// ------------------
// nest an element within the nested div
nested.insertAdjacentHTML(`afterbegin`,
`<div id="nestedWithin#nested">
This text will appear <i>above</i> the text of
my parent, that being div#nested.
Someone had the nerve to insert me using
<code>insertAdjacentHTML</code>
</div>`);
// Object.assign
// -------------
// Use Object.assign to create an element and
// assign properties/html to it in one go
const newElem = Object.assign(
document.createElement(`div`),
{ id: `myBrandnewDiv2`,
innerHTML: `div#myBrandnewDiv2 signing in.
I was <i>assigned</i> using <code>Object.assign</code>…`});
document.body.appendChild(newElem);
// insertAdjacentElement combined with Object.assign
// -------------------------------------------------
// use the above technique combined with insertAdjacentElement
newElem.insertAdjacentElement(
`beforeend`,
Object.assign(document.createElement(`span`),
{ id: `myBrandnewnested2_nested`,
innerHTML: `<br>Me too! And appended I was
with <code>insertAdjacentElement</code>` })
);
// createDocumentFragment
// ----------------------
// Use a document fragment to create/inject html
const fragment = document.createDocumentFragment();
const mdnLnk = `https://developer.mozilla.org/en-US/` +
`docs/Web/API/Document/createDocumentFragment`;
fragment.appendChild(
Object.assign(
document.createElement(`p`),
{innerHTML: `Regards from <code>createDocumentFragment</code>
(see MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<div id="id2">Hi!</div>
<p id="id3">Hi 2!</p>`,
classList: [`xyz`], } );
const prepareHtml4Reporting = html =>
html.replace(/</g, `<`)
.replace(/\n\s+/g, `\n`)
.replace(/\n\n/g, `\n`);
document.body.insertAdjacentHTML(
`beforeend`,
`<h3>html only</h3><pre>${
prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}
code {
background-color: #eee;
}
.nested {
margin-left: 0.7rem;
max-width: 450px;
padding: 5px;
border: 1px solid #ccc;
}
I have used some of these methods in this library (see /src/DOM.js), with a mechanism for sanitizing html before it is injecting.
Html:
<div id="main"></div>
JavaScript:
var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));
var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));
tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);
The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.
At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)
With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.
Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.
If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.
If you want to create three unrelated elements, you can do:
var anchor = elem("a", {"id":"id1"});
var div = elem("div", {"id":"id2"});
var xyz = elem("div", {"id":"id3"});
Now, you have three elements. If you want to get the HTML of these (as string), simply do:
var html = anchor.outerHTML + div.outerHTML + xyz.outerHTML;
If you want to have these three in an element (say, div), do:
var div = elem("div", null, [
elem("a", {"id":"id1"}),
elem("div", {"id":"id2"}),
elem("div", {"id":"id3"}),
]);
You can get the HTML with div.outerHTML, or you can just append it anywhere you want.
To know more about elem(), visit element.js (GitHub).
I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.
You can construct the html as a string in one variable like
var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on
then you return the variable html
return html;
The better way would be to Import ElementsJS and just reference each element in it.
var root = document.getElementById("root");
var elementdiv = create_element('div',{'class':'divcss'}, root, null);
create_element('h1',{'class':'hellocss'}, elementdiv, "Hello World");
.hellocss {
color : red;
}
.divcss {
background-color : blue;
height: 100px;
position: absolute;
}
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>
For More Details Refer to https://github.com/divyamshu/Elements-JS
Well Documented with Example.
Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).
Let us say, you have html-page as "index.html" (calling index_static.html here).
index_static.html
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1> Hello !!! </h1>
</body>
</html>
You can open this file in the browser, to see the desired output.
Now, lets create a javascript equivalent to this.
Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:
dynamic.js
document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write(" <head>");
document.write(" <title>Test<\/title>");
document.write(" <\/head>");
document.write(" <body>");
document.write(" <h1> Hello !!! <\/h1>");
document.write(" <\/body>");
document.write("<\/html>");
And now, your dynamic version of the static_index.html will be as below:
index_dynamic.html
<script language="JavaScript" src="dynamic.js"></script>
Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).
more info

Buttons with JavaScript

I'm new in JavaScript, html and CSS and I'm trying to make a simple web page about Formula 1. In this page I was trying to make a small menu with 10 buttons, each one of them would lead you to a formula one team web page. I was doing using only html the first time but then realize I probably could do it using a loop in JavaScript and save a lot of lines and time, I have some thoughts about how to do it but I don't know how to execute the idea properly.
First I would create a list of 10 objects, each object with an image link and the web page of one of the 10 teams to use in the buttons:
var teams = [
{name: mercedes, logo: teammercedes.icon, web: mercedes.com
{name: ferrari, logo: ferrari.icon, web: ferrari.com}
Then would create a "for" (I'm guessing here)
for(i = 0; i < 11; i++){
Now, I have no idea how to put this in JS but I here is what I want:
mercedes is i = 0, so the JS create all the button tag structure using
the Mercedes logo I saved in the list above to decorate de button.
then it goes to i = 1, which would be Ferrari, and the JS create again
all the button tag structure using the Ferrari logo saved in the list
}
I think by this method I would need to write the button structure once in the JS and, somehow, push the information inside of it 10 times, using 10 different index defined on a list
You're on the right lines. Create an array of companies, and then iterate over the names to build some HTML, and then attach it to a menu. Use some CSS to style the buttons.
This example uses some modern JS techniques that aren't meant to scare you off, I promise. There's full documentation at the end of the answer, but I'll try and explain things along the way.
// The array of companies that you wanted
const companies = ['Mercedes', 'Renault', 'Saab', 'Fiat'];
// We cache the menu element using `querySelector`
const menu = document.querySelector('#menu');
// We assign a listener to the menu so when it is clicked
// we can redirect to a new page based on the the button id
menu.addEventListener('click', handleClick, false);
// For the buttons we can `map` over the array and create
// a new array of HTML that we `join` into a string at the end.
// I've used a dummy image here, but you can substitute in your
// own images for the img source
const buttons = companies.map(company => {
const src = `https://dummyimage.com/100x30/b5d19d/000&text=${company}`;
// Return some HTML that uses a class, a data attribute for
// the company name, and the src image for the "button", and
return `<img class="company" data-id="${company.toLowerCase()}" src="${src}" />`;
// then `join` the new array up into one string
}).join('');
// Add the button HTML to the menu element
menu.innerHTML = buttons;
// When the listener is called
function handleClick(e) {
// Grab the id value from the data attribute, and
// the className from the element that was clicked
// using destructuring assignment
const { dataset: { id }, className } = e.target;
// Check to see if the element that was click was a button
if (className === 'company') {
// And then navigate to your new page
console.log(`http://example.com/${id}.html`);
// window.location.href = `http://example.com/${id}.html`;
}
}
.company { border: 1px solid white; border-radius: 10px; display: block; margin: 1em; cursor: pointer; }
.company:hover { border: 1px solid black; }
<div id="menu"></div>
Additional documentation
querySelector
map
addEventListener
Template/string literals
Destructuring assignment
join
Data attributes
You did not specify where to insert elements(DOM string) generated by JavaScript. So, the code below inserts elements into body tag as an example.
var teams = [
{name: "mercedes", logo: "teammercedes.icon", web: "mercedes.com"},
{name: "ferrari", logo: "ferrari.icon", web: "ferrari.com"}
];
let body = document.querySelector('body');
for (let i = 0; i < teams.length; i++) {
let link = teams[i].web;
let logo = teams[i].logo;
let name = teams[i].name;
body.insertAdjacentHTML('afterbegin', `<img src="${logo}" alt="${name}" />${name}`);
}
Although you think using JavaScript is an good way to list elements, I disagree. The JavaScript code runs in the browser. That means, the list of buttons will not be recognized until JavaScript runs.
Therefore, I believe it is better to return the list of buttons included in a HTML document.

Append additional html to cloned object in jquery

I want to add additional html in the cloned object.
var item = $("#clone")
.clone(true, true)
.attr({"id": "citem", "class": "row cartItem_" + item_id})
.css('display', 'block')
.appendTo("#all-items");
I know about wrap method but that is something else. I want to append html after this cloned object. Or somehow i can manipulate the HTML of the cloned object element.
This approach is to explain how the .clone() works, and covers all the states you ever mentioned in the question, such as..
Creating a clone of a DOM
Appending additional raw HTML to a clone
Manipulating the clone
Manipulating the content in the clone
Clone in another clone
Appending another clone to a clone
Appending HTML after this cloned object
$(function() {
//! Cloning the HTML
var $clonedContent = $('.content').clone();
// Manipulate the cloned element
// -- Update the existing content
$clonedContent.find('h5').text("My content just got manipulated");
// -- Adding raw HTML content
$clonedContent.append("<small> It's a raw HTML </small>");
// -- Adding property to an existing content
$clonedContent.find('small').addClass('make-me-day');
//! Getting another cloned content
var $anotherClonedContent = $('.content').clone();
// -- Another manipulation of another cloned content
$anotherClonedContent.find('h5').text("This is another cloned content");
// -- Manipulate the another cloned content's content
$anotherClonedContent.find('h5').addClass('make-me-day');
// -- Add another cloned content to the already manipulated & cloned content.
$clonedContent.append($anotherClonedContent);
//! Finally, add the clonedContent to the DOM, aaaand.. add more HTML afterwards.
$('#main').append($clonedContent, "<em> I added this HTML after the cloned object </em>");
});
.make-me-day {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="content">
<h5> Just a simple content </h5>
</div>
</div>
Assuming you are trying to add html after the clone:
$("#toclone")
.clone()
.attr({"id":"cloned"})
.appendTo("#all-items")
.after("<div>some more content <em>after</em> the clone</div>");
The .appendTo() returns the element that was appended, so you can then manipulate it as required, eg using .after()
I think that's more easy than you imagine:
$(function(){
var item_id=0;
// function to clone your element
var newItem=function(){
item_id++;
return $('#clone')
.clone(true, true)
.attr({'id':'citem_'+item_id, 'class':'row cartItem_'+item_id})
.css('display','block')
.appendTo('#all-items');
};
// Clone element and edit what you want
newItem().html('hobby').css('color','blue');
// Clone element and append what you want
newItem().append(' - <i>spaghetti</i>');
// You can also find element by id
$('#citem_2').css('color','red');
//You can add buttons to do it
$('button:eq(0)').on('click',function(){
newItem().html('Your <b>html</b> here.');
});
$('button:eq(1)').on('click',function(){
newItem().append(' - Your <b>html</b> here.');
});
});
<button>New clone</button>
<button>New clone + append</button>
<div id="all-items">
<div id="clone">pizza</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I took a close look to all answers and comments to this bounty question...
I can see that the bidder is kind of demanding, which is okay since 100 rep. points is valuable.
I think that the question contains two, in fact.
How to clone
How to «manipulate the HTML of the cloned object» - Wasif Iqbal on Sep 22th.
I think the question is intended to get explanations on how to manipulate the clone, not only on creation and appending to somewhere, but also afterward.
I really think my very cool example below could be a «valid answer» - Vixed on Sep 29th.
The other answers were good too, anyway... So a made a supplemental effort. ;)
First explanation of all:
Cloning an element is done by jQuery .clone(). So have a nice reading.
Then:
jQuery chaining is nice to append some other stuff «inside» or «before/after» the clone in a concise way, as demonstrated in other answers.
But to manipulate it afterward, like in another click event handler...
This is the trick to know, which is not explained in the previous reference:
You have to make sure to set a unique id attribute to it, instead of the same id as the original.
Because you know that an id shall be unique!
«One ring to rule them all.
One ring to find them, one ring to bring them all and in the darkness bind them.»
- A well known deamon said this while forging a curse...
Then... What more explanation could I give if it ain't clear?
Alert reader should have understood everything already.
I made a funny «clone-and-kill-it-game» to demontrate cloning and further manipulations.
For the «inspiration», I have to admit that I saw a japaneese zombie movie yesterday night...
lol!
Have fun with this code snippet:
(also on CodePen)
// Constants
var number = 1;
var revealed = false;
// The cloning function
$("#cloneIt").click(function(){
var cloning = $("#Human")
.clone()
.attr({"id": "Clone_number_"+number, "class":"clone"})
.appendTo("#CloneBucket");
$(this).val("Clone him again! It's fun!");
number++;
if(number==4){
$(".reveal").show();
}
if(number==9){
$(this).val("Enought! This is now illegal.").prop("disabled",true);
}
// Add them to select
var options="<option disabled selected class='deceased'>KILL THEM!</option>";
for (i=1;i<number;i++){
if( $("#CloneBucket").children().eq(i-1).hasClass("dead") ){
options += "<option value='"+i+"' class='deceased'>Clone #"+i+"</option>";
}else{
options += "<option value='"+i+"'>Clone #"+i+"</option>";
}
}
$("#cloneSelect").html(options);
if(revealed){
reveal(); // Sub function to add clones to a select element.
}
});
// Reveal clone numbers
$(".reveal").click(function(){
reveal();
setTimeout(function(){
$(".reveal").val("Kill a clone! (While it's not illegal!)").removeClass("reveal").addClass("shoot");
},50);
});
// Kill button
$("#page").on("click",".shoot",function(){
$(this).prop("disabled",true).val("Select one");
$("#cloneSelect").show();
});
// Select kill target
$("#cloneSelect").change(function(){
var thisCloneIs = parseInt($(this).val());
var niceShot = "#Clone_number_"+thisCloneIs;
$(niceShot).css({"opacity":0.3,"color":"red"});
$(niceShot+" .definition").html("I was the number"+thisCloneIs).parent().addClass("dead");
// Redish the option
$(this).find("option").eq(thisCloneIs).prop("disabled",true).addClass("deceased");
$(this).find("option").eq(0).prop("selected",true);
// Bravo!
var allDead = [];
setTimeout(function(){
$("#cloneSelect").find("option").each(function(index){
if( $("#cloneSelect").find("option").eq(index).hasClass("deceased") ){
allDead.push(true);
}else{
allDead.push(false);
}
});
if( allDead.indexOf(false)==-1 ){
// Reset this super gaming experience for a new.
$("#CloneBucket").html("");
$(".shoot").addClass("reveal").removeClass("shoot").val("Reveal clone numbers!").prop("disabled",false).hide();
$("#cloneIt").val("Clone again?").prop("disabled",false);
$("#cloneSelect").html("").hide();
revealed = false;
number = 1;
}
},50);
});
function reveal(){
$(".clone .definition").each(function(index){
var cloneIndex = index+1; // zero-based
$(this).html("I'm the number "+cloneIndex);
revealed = true;
});
}
img{
width:60px;
}
div{
text-align:center;
}
.reveal{
display:none;
}
#CloneBucket div{
display:inline-block;
padding:10px;
}
#CloneBucket{
margin:0 auto;
text-align:center;
}
select{
display:none;
margin:0 auto;
}
.deceased{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="page">
<input type="button" id="cloneIt" value="Want to clone him?"><br>
<br>
<div id="Human">
<img src="http://image.flaticon.com/icons/svg/10/10522.svg"><br>
<span class="definition">I'm a real human!</span>
</div>
<br>
<input type="button" class="reveal" value="Reveal clone numbers!">
<select id="cloneSelect"></select>
<div id="CloneBucket"></div>
<br>
</div>
Still waiting for clarification in the comments, but I think this solution is what you are looking for:
$('button').click(function() {
$('#clone').clone()
.append('<span style="color:red;">some other elements</span>')
.removeAttr('id')
.appendTo('#all-items');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Click to clone</button>
<div id="all-items">
<div id="clone">pizza</div>
</div>
Since the appendTo returns the original element that was appended, you can use after on the returned value to add some new element after the cloned element that you just appended:
$('button').click(function() {
$('#clone').clone()
.append('<span style="color:red;">some other elements</span>')
.removeAttr('id')
.addClass('cloned')
.appendTo('#all-items')
.after('<div>this element was added after the cloned element (no blue border here)</div>');
});
.cloned {
border: 1px solid blue;
margin: 5px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Click to clone</button>
<div id="all-items">
<div id="clone">pizza</div>
</div>
One can add to a collection at any time using jQuery's add() function.
This effectively adds to the collection, placing whatever is passed to add() after the clone itself, as opposed to append which places the content inside the clone, answering the question
"I want to append html after this cloned object"
var more1 = $('<span />', {html : '<em> and will</em>'}); // element(s) to add
var more2 = '<span> happen again....</span>'; // or strings of HTML for that matter
var item = $("#clone").clone(true, true)
.attr({"id": "citem"})
.show()
.add(more1) // add whatever after the clone
.add(more2) // before appending everything
.appendTo("#all-items");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="clone">
<span>All of this has happened before</span>
</span>
<br /><br /><br />
<div id="all-items"><!-- clone goes here --></div>
From the documentation
Given a jQuery object that represents a set of DOM elements, the
.add() method constructs a new jQuery object from the union of those
elements and the ones passed into the method.
The argument to .add()
can be pretty much anything that $() accepts, including a jQuery
selector expression, references to DOM elements, or an HTML snippet.
example : $("p").clone().add("<span>Again</span>").appendTo(document.body);
add() does not change the original collection, but returns a new collection, so if not chaining directly on the modified collection, one has to store that collection
var clone = $('#elem').clone(true, true);
var changed = clone.add('<div>new content</div>'); // clone is not changed
Manipulating the content inside a clone is done in the exact same way as manipulating any other collection with jQuery
Post something link this
var clone = parent.find('.divclone').clone();
clone.removeClass('identifier');
clone.removeClass('hide');
//.. code changes for the new clone
clone.find(".link-slug").attr('href',invstr_val.slug_url);
// append it again to the original
clone.insertAfter(parent.find(".divclone"));

Categories