Instantiate new element class using javascript - javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.

You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.

var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.

With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}

Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Related

How to Change Color of Div within a for statement?

Inside my php while loop I output a div with id divborder, and class div-border
Inside that div i have another div with id title
<div id='divborder' class='div-border'>
<div id='Title'>This is Title</div> <br/> video elements
</div>
I have a JavaScript function that get called when the video ends
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
}
My Question is how do i change the border color of the div and the title of second div?
I can do it like this:
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
which works but its not dynamic
Save the value of value at i in another variable declared with let
for (var i = 0; i < videos.length; i++) {
let index = i; //save the value as let so that its binding stays
videos[i].addEventListener("ended", function(event)
{
var divBoader = document.querySelectorAll("div-border")[index];
divBoader.style.borderColor = "#b1ff99";
}
}
Or if the video elements are within the div-border, then use closest
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader = event.currentTarget.closest(".div-border");
divBoader.style.borderColor = "#b1ff99";
}
}
A little less verbose code
[...videos].forEach( s => s.closest( ".div-border" ).style.color = "#b1ff99" )
Try this,
Give class name div-border instead of divborder
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("div-border")[3];
divBoader2.style.borderColor = "#b1ff99";
}
What you need is probably a videos[i].parentNode instead of document.getElementsByClassName("div-border")[3] (see https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode)

appendChild not working on divs in a loop

I am trying to append new div elements to existing divs by using document.getElementsByTagName("div"), converting it to an array, then using appendChild on it. However, when I inspect the frame source of this jsfiddle, it doesn't seem to append it to the divs. It is just:
<body>
<div id="1">
<div id="2">
test
</div>
</div>
Instead of the expected result:
<body>
<div id="1">
<div id="2">
test
</div><div></div>
</div><div></div>
https://jsfiddle.net/ng58e87w/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
I can't comment, but I believe you are just creating empty divs and adding nothing to them. They show up created when you inspect element in the jsfiddle. I also set their text to something and it seemed to work.
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hidden Div?";
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
Use .after() instead of .appendChild().
var words = ['apple','banana','cake'];
console.log(words[0]);
object1 = {
name:'frank',
greet:function(){
alert('hello '+this.name)
}
};
object2 = {
name:'andy'
};
// Note that object2 has no greet method.
// But we may "borrow" from object1:
object1.greet.call(object2);
/*
var divs = [];
var arr = Array.prototype.slice.call( document.getElementsByTagName("div") );
for(var i = 0; i < arr.length; i++) {
//do something to each div like
var div = document.createElement("div");
arr[i].appendChild(div);
}
*/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].after(newDiv);
console.log(allDivs[i]);
}
<div id="1">
<div id="2">
test
</div>
</div>

Writing HTML for a string of values using javascript and jquery?

I want to have my page's html to appear as:
<div class='container'>
<div class='domain-list0'>Hello</div>
<div class='domain-list1'>World</div>
</div>
Here is my html and js: Pen from Codepen.io
Instead of creating the first "domain-list" and then creating another one for the next, it is just overwriting the previous "domain-list". This is why it shows the last string value. Anyone know how to fix this?
Thanks!
You are using .html() which removes the existing content, and replaces it with the new content. You need to use append so that the new content is added after the last child.
var myStringArray = ["Hello", "World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
var $el = $("<div />", {
'class': 'domain-list' + i,
html: "<p>" + myStringArray[i] + "</p>"
}).appendTo("div.container");
// $el refer to the newl added element
}
Demo: Fiddle
use .appendTo() so that it will return the newly created element which can be used for further processing
for (var i = 0; i < arrayLength; i++) {
$("div.container").html("<div class='domain-list'></div>");
$(".domain-list:nth-child("+i+")").html("<p>"+myStringArray[i]+"</p>");
//Do something
}
Try to use appendTo in jquery
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
$("<div class='domain-list"+i+"'></div>").html("<p>"+myStringArray[i]+"</p>").appendTo("div.container");
//Do something
}

Access elements in ul list

I have the following list hierarchy:
<ul id="ulid">
<li><a><div class="mydiv">content</div></a></li>
<li><a><div class="mydiv">content</div></a></li>
...
</ul>
I want to add some css rules to the div and this is what i've tried so far:
var myul = document.getElementById("ulid");
var myli = myul.getElementsByTagName("li");
for(var i = 0; i < myli.length; i++) {
//myli[i].parentNode.style.display = "none"; // that works
var links = myli[i].getElementsByTagName("a");
for(var ii = 0; ii < links.length; ii++) {
links[ii].parentNode.style.display = "none"; // doesnt work
}
}
I can hide the li items but cant do the same for a So i cant reach the div. What am i doing wrong here?
EDIT: getElementsByClassName seems not working in greasemonkey scripts as it simply works in Emmanuel N's fiddle.
Your code seems to work. Check out this Fiddle
var myul = document.getElementById("ulid");
var myli = myul.getElementsByTagName("li");
for(var i = 0; i < myli.length; i++)
{
var links = myli[i].getElementsByTagName("a");
for(var ii = 0; ii < links.length; ii++)
{
links[ii].parentNode.style.display = "none";
}
}
Your code actually does work, but I don't think it does what you're intending it to do. The last line: links[ii].parentNode.style.display = "none" will actually hide the parent node of the a tag (i.e. the li) tag, rather than the div. parentNode will go one level UP, not down.
Instead of trying to get myli[i].getElementsByTagName("a") and then working down to the div, why not myli[i].getElementsByTagName("div"), and then simply do:
var myul = document.getElementById("ulid");
var myli = myul.getElementsByTagName("li");
for(var i = 0; i < myli.length; i++) {
//myli[i].parentNode.style.display = "none"; // that works
var links = myli[i].getElementsByTagName("div");
for(var ii = 0; ii < links.length; ii++) {
links[ii].style.display = "none";
}
}
Of course, there are many more efficient ways to do it. You already have classnames on the divs, so
document.getElementsByClassName("mydiv");
would work just as well.
Or, if you use jQuery, you can do the same thing without having to iterate explicitly:
$("div.mydiv").css(etc.); // style this however you want
If you aren't opposed to using jQuery, the following would hide your divs for you.
$(document).ready(function () {
var myDivs = $('div.mydiv');
for(var eachDiv in myDivs) {
$(eachDiv).hide();
}
});

How to add DOM Element in for loop

How can I create new Element each time when (i) will be incremented:
for(int i = 0; i < 10; i++)
{
Element child = doc.createElement("xxx");
root.setAttribute("x", i * "xx");
doc.appendChild(child);
}
Using pure js
var div = document.getElementById("main");
for (var i = 0; i < 10; i++) {
var span = document.createElement("span");
span.setAttribute("class", "new");
span.innerHTML = "span" + i;
div.appendChild(span);
}​
HTML
​<div id="main"></div>​​​​​​​
Working example.
Cheers!!
Using java
Element child = null;
for(int i = 0; i < 10; i++)
{
child = doc.createElement("xxx" + i);//you can write a method with int parameter to get element name from somewhere else
doc.appendChild(child);
}
I hope this is what you wanted, by the way for text nodes you should use doc.createTextNode("A")

Categories

Resources