I've been trying to dynamically append a div to inside multiple other divs:
SoundCloudAPI.renderTracks = function createCards(){
var card = document.createElement('div');
card.classList.add("card");
var searchResults = document.querySelector('.js-search-results');
searchResults.appendChild(card);
var imageDiv = document.createElement('div');
imageDiv.classList.add("image");
var imageResults = document.querySelector('.card');
imageResults.appendChild(imageDiv);
}
however, it only appends to the first "card"
div in my body.
What's the problem here?
querySelector will return the first element with this class, so you have to use querySelectorAll , then loop throught the found element using foreach to append you element as below
SoundCloudAPI.renderTracks = function createCards(){
var card ;
var searchResults = document.querySelectorAll('.js-search-results');
// loop using foreach
searchResults.forEach(function(searchResult) {
card = document.createElement('div');
card.classList.add("card");
searchResult.appendChild(card);
});
var imageDiv;
var imageResults = document.querySelectorAll('.card');
// loop using foreach
imageResults.forEach(function(imageResult) {
imageDiv = document.createElement('div');
imageDiv.classList.add("image");
imageResult.appendChild(imageDiv);
});
}
Related
what I want something like this
var newDiv = document.createElement("div");
newDiv.innerHTML = data;
var List=newDiv.$(".myclass h4");
console.log($(List[0]).html());
but it doesnot work.
If you make that newDiv a jQuery object, and then use find(), you can get the other element within it.
$(newDiv).find(".myclass h4");
Stack snippet
var data = "<div class='myclass'><h4>hello</h4></div>"
var newDiv = document.createElement("div");
newDiv.innerHTML = data;
var List = $(newDiv).find(".myclass h4");
console.log( $(List).html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An alternative is passing as the second parameter the created element as the parent/source DOM element to find elements from it.
$(".myclass h4", newDiv); <--- This call returns a jQuery object.
^
|
+--- Parent/Source element
var newDiv = document.createElement("div");
newDiv.innerHTML = '<div class="myclass"><h4>Ele from Stack</h4></div>';
var list = $(".myclass h4", newDiv);
console.log(list.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This question already has answers here:
one document.createElement, append it twice, only shows once
(2 answers)
Closed 4 years ago.
I'm writing a function to create two cards -one is square and another round in shape to display on a button's click. When another button is pressed, few more styles gets added.
But the problem I'm running into is that the div squareMainID and roundMainID both of them have same number of divs within divs. When the div gets displayed on the DOM, only roundMainId's div tags and children shows up(see image). If you can see the dev tool, the black arrows next to the roundMainID is collapsable. Not the same for SqaureMainID. Even the styles that I'm trying to apply gets applied only to the roundMainID and not to the square. Why is this happening and how to fix?
code:
var pick= document.getElementById("pick");
var attachCardsDiv = document.createElement("div");
attachCardsDiv.className += "attach-cards-div"
var squareMainDiv = document.createElement("div");
squareMainDiv.className = "cardsPanel";
squareMainDiv.setAttribute("id", "squareMainID");
var roundMainDiv = document.createElement("div");
roundMainDiv.className = "cardsPanel";
roundMainDiv.setAttribute("id", "roundMainID");
var classADiv = document.createElement("div");
var classBDiv = document.createElement("div");
var apple = document.createElement("div");
var banana = document.createElement("div");
function attachTwoCardsOnDom(){
classBDiv.appendChild(banana);
classBDiv.appendChild(apple);
classADiv.appendChild(classBDiv)
squareMainDiv.appendChild(classADiv).addEventListener('click',
function(event){
console.log("clicked");
});
attachCardsDiv.appendChild(squareMainDiv);
document.body.appendChild(attachCardsDiv);
// ************************************************************
classBDiv.appendChild(banana);
classBDiv.appendChild(apple);
classADiv.appendChild(classBDiv)
roundMainDiv.appendChild(classADiv).addEventListener('click',
function(event){
console.log("clicked");
});
attachCardsDiv.appendChild(roundMainDiv);
document.body.appendChild(attachCardsDiv);
}
pick.addEventListener('click', function(event){
attachTwoCardsOnDom();
})
html:
<button id="pick">Press</button>
In:
var classADiv = document.createElement("div");
var classBDiv = document.createElement("div");
var apple = document.createElement("div");
var banana = document.createElement("div");
You create the divs just once and then in:
function attachTwoCardsOnDom(){
classBDiv.appendChild(banana);
classBDiv.appendChild(apple);
classADiv.appendChild(classBDiv)
you just move them around.
That is, you actually are adding to squareMainDiv, but later you are removing them from it when adding the divs to roundMainDiv.
Fix: You have to recreate the divs every time:
function attachTwoCardsOnDom(){
var classADiv = document.createElement("div"); // creating here
var classBDiv = document.createElement("div"); // creating here
var apple = document.createElement("div"); // creating here
var banana = document.createElement("div"); // creating here
classBDiv.appendChild(banana);
classBDiv.appendChild(apple);
classADiv.appendChild(classBDiv)
squareMainDiv.appendChild(classADiv).addEventListener('click',
function(event){
console.log("clicked");
});
attachCardsDiv.appendChild(squareMainDiv);
document.body.appendChild(attachCardsDiv);
// ************************************************************
var classADiv2 = document.createElement("div"); // creating here, different name
var classBDiv2 = document.createElement("div"); // creating here, different name
var apple2 = document.createElement("div"); // creating here, different name
var banana2 = document.createElement("div"); // creating here, different name
classBDiv2.appendChild(banana2); // notice classBDiv2 (2!)
classBDiv2.appendChild(apple2); // and on...
classADiv2.appendChild(classBDiv2)
roundMainDiv.appendChild(classADiv2).addEventListener('click',
function(event){
console.log("clicked");
});
attachCardsDiv.appendChild(roundMainDiv);
document.body.appendChild(attachCardsDiv);
}
Demo JSFiddle: https://jsfiddle.net/acdcjunior/s41ax3rb/3/
I created different elements-paragraphs with createElement()/createTextNode() and added them to the body.
My problem is that i want to make those divs links or be able to add events such as onclick and obviously there is no HTML code to do that..just javascript generated objects.
my code atm:
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode(data[1][i]);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode(data[2][i]);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
You can add the event listener to the object you just created. The object does not have to be HTML. Read more about adding event listeners and see simple example:
var someDiv = document.createElement('div');
var txt = document.createTextNode('click me');
someDiv.append(txt);
document.body.append(someDiv);
var myFancyFunction = function() {
alert('you clicked me');
};
someDiv.addEventListener('click', myFancyFunction);
Update after your code you can add an event listener to those objects you create on the fly. You can also add different functions on the same event. In this case it's the same function for both elements/objects .. play with this: (I changed the data to "dummy data" as there was no data)
var myClick = function(event) {
alert(event.target.innerHTML);
};
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode('dummy data1 index: ' + i);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode('dummy data2 index: ' + i);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
heading.addEventListener('click', myClick);
paragraph.addEventListener('click', myClick);
}
You can simply call addEventListener on the JS-generated objects, even before they are inserted into the DOM, or are never inserted at all:
let div = document.createElement('div');
div.addEventListener('click', function(event) {
// do something
});
// This will trigger a call of the registered click callback,
// regardless of whether the div is in the DOM:
div.dispatchEvent(new Event('click', {
"bubbles": true,
"cancelable": false,
}));
// To add it to the DOM, simply add it the way you wish:
document.body.appendChild(div);
EventTarget.dispatchEvent allows you to trigger an event in a computational way (has equivalent effect to actually clicking the div)
Do take note of the browser compatibility of the event constructor in the example above.
Once an element is added to the dom, you can select it just like any other element.
// Create the element
var paragraph = document.createElement('p');
// Give it an `id`
paragraph.id = 'foo';
// Add the element to the `dom`
document.body.appendChild(paragraph);
// Add the listener
paragraph.addEventListener('click', function() {
this.innerHTML = 'It was clicked';
});
p {
height:20px;
padding:10px;
outline:1px solid #bada55;
}
In the example above, I added an id. If for some reason you need to re-select the element it may make it easier.
I have some id div with elements(classes and Ids), I need to clone it and append to my clone new class. How can I do it?
window.onload = Func ();
function Func () {
var temp = document.getElementById("start");
var cl = temp.cloneNode(true);
var div = document.createElement('div');
div.className = "class";
div.innerHTML = "MyText";
var result = cl.getElementById("second").append(div);
alert(result.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="start">
<div id="second">
Link
</div></div>
use following code
$(function(){
var $Div = $('.start').clone();
$('.second').html($Div);
});
Using JQuery,
var clone = $("#divName");
or var clone = $(".className")
var secondDiv = $("#secondDiv");
or var secondDiv = $(".secondDivClassName");
//Or you can get the html of your second div like this:
var myHtml = secondDiv.html(); //if you don't give any parameter, it takes the inner html of the given element.
//and finally insert your html into the clone like this :
clone.html(myHtml);// in this case, the html() methode takes a parameter and inserts the given parameters into the given element.
You should reference JQuery to your page.
Tell me if it works.
How to create div in javascript for each create elements(DOM) and retrieve their values?
for (i = 1; i <= 3; i++) {
var input = document.createElement('input');
input.setAttribute("id", "x" + i);
var div = document.createElement('div');
div.id = "div"+i;}
I'm assuming you want to append all of your inputs into your divs and then your divs into the body.
Use the function appendChild, which is available on all DOM nodes, furthermore, your code will not work since inputVN is undefined.
you can try with this
document.body.appendChild(element);
example for create a div with javascript
var Div = document.createElement('div');
Div.id = 'DivId';
document.body.appendChild(Div);
this is a little example how create a div, you can try with these