I have a body element, and in this body element I have a child element with id fullpage. And this element contains child element with classname section. In function load_works() I add two more section elements
<body>
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>
<script src="js/main.js" charset="utf-8"></script>
<script type="text/javascript">
load_works();
</script>
</body>
Contents of main.js:
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
The problem is, that when I try to count section elements with getElementsByClassName() like this after load_works() is executed
function some_function() {
var sections = document.getElementsByClassName('section');
console.log(sections.length);
}
it always returns 1, and this, I think, is because I have only one static section element. querySelectorAll() of course and other get- fucntions also aren't working. So, how can I achieve the correct result with pure Javascript, not jQuery?
You better should place all javascript inside one file like main.js and then you only need to call some_function() after load_works().
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
function some_function() {
var sections = document.getElementsByClassName('section');
alert(sections.length);
}
load_works();
some_function();
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>
Related
I want to repeat 'post' div and all of its contents eg 50times in left-col div using jquery and call it inside html?
HTML:
<div class="post"> Content </div>
JS:
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
$(document).ready(function(i) {
for (let i = 2; i < 100; i++) {
$(".post:eq(0)").clone().appendTo(".left-col");
}
});
You can do it like this:
$(document).ready(function(i) {
for (let i = 0; i < 50; i++) {
$(".post:eq(0)").clone().appendTo("#left-col");
}
});
There was a few problems with your code. First $("#post") should be $(".post"), since it's a class not an id.
Second your for loop was not correct. You were missing the {} and also it should be i < 50 not i < i.length(50)
Also important to note that I've added :eq(0) to $(".post"), since it would cause a big problem without.
Because first time the loop would run, you would have 1 element with the class post, second time you would have 3 elements, third time = 6 elements and so far.
$(document).ready(function(i) {
for (let i = 0; i < 50; i++) {
$(".post:eq(0)").clone().appendTo("#left-col");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post"> Content </div>
<div id="left-col"></div>
I get null when I try to do getelementbyid on dynamic loaded in div
I tried window.onload = function () { and $(window).load(function() {
index.html:
<main >
<div id="main-div">
</div>
</main>
homepage.html:
<!-- categories Slider -->
<div class="container-fluid">
<div class="site-slider-two px-md-4">
<div class="row slider-two text-center" id="homepageCategories">
javascript:
function loadHomePage() {
$("#main-div").load("homepage.html", function () {
}
}
function showCategoriesHomepage(categories) {
window.onload = function () {
homepageCategoriesId = document.getElementById(homepageCategories);
homepageCategoriesId.innerHTML = "";
//For loop that loops true all the categories
for (var i = 0; i < messages.length; i++) {
//Create dynamic li elements with child p elements
var mainDiv = document.createElement('div');
var span = document.createElement('span');
var img = document.createElement('img');
span.setAttribute("class", "border site-btn btn-span");
img.setAttribute("src", categories.image);
//Fills the p elements with user_id, description, created_at
span.appendChild(document.createTextNode(categories.name));
mainDiv.appendChild(img);
mainDiv.appendChild(span);
}
}
After the homepage is loaded I make a call to the api and after that is finished I try to getelementbyid on the div but it returns null
Change this line...
homepageCategoriesId = document.getElementById(homepageCategories);
...to this
homepageCategoriesId = document.getElementById('homepageCategories');
When I try to dynamically fill a wrapper element with HTML elements, and then add an EventListener for that element, it only uses the last value.
window.onload=function(){
sW="";
for(var i = 0; i < 5; i++) {
var e = document.createElement('div');
e.innerHTML = "test div number "+i;
e.addEventListener('click', function() {alert("t:"+i);});
document.getElementById('wrap').appendChild(e);
}
}
<html>
<body>
<div id="wrap"></div>
</body>
</html>
That's because var keeps the the reference to the variable. Use let instead.
Only JS no Jquery.
How to get All ChildNodes of container and than for each of the children get there children?
I don't want to add ID to each Wrapper that is child of grid-row, I am trying to target with "this" or at this index. This script should be dynamic without specifying any ID.
I can't use classes to get all Wrappers as I need to trigger each wrapper separately and apply changes to it.
I want to get all grid-row children "Wrapper" widths and store in a array.
I am using ChildNodes as it is compatible with all browsers.
var container = document.getElementById('container');
var rows = container.childNodes;
var rowslenght = container.childNodes.length;
var rowsArray = new Array();
for (var i=0; i < rowslenght ; i++) {
if (gridrow[i].nodeType == 1){ // this is to no retrieve text
// I got all the children of grid-row. How I get grid-row children.
// var rowsChildren = rows[i].getAttribute('id');
// here goes other if to go through each "Wrapper" width and set width
// console.log( rowsChildren);
console.log( rows);
return rowsArray;
}
}
<div id="container">
<div class="grid-row">
<div class="Wrapper">
<div class="block"></div>
</div>
<div class="Wrapper">
<div class="block"></div>
</div>
</div>
<div class="grid-row">
<div class="Wrapper">
<div class="block"></div>
</div>
<div class="Wrapper">
<div class="block"></div>
</div>
</div>
</div>
Try this.
var container = document.getElementById('container');
var rows = container.childNodes;
rows = removeTextNode(rows); // remove Text Nodes;
// Loop through .grid-row
forEach(rows, function(row){
// Get wrappers and filter them
var rowWrappers = row.childNodes;
rowWrappers = removeTextNode(rowWrappers);
// Now loop over the wrapper, and modify
// the current function adds `Wrapper-blue` to the wrappers.
forEach(rowWrappers, function(wrapper){
console.log(wrapper);
wrapper.classList += ' Wrapper-blue';
});
});
// this helper function removes extra spaces/breaklines which are considered as Nodes
function removeTextNode(nodes){
return [].filter.call(nodes, function(o){
return o.nodeType == Node.ELEMENT_NODE;
});
}
// Source: https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
function forEach(array, callback, scope) {
for (var i = 0; i < array.length; i++) {
// the first argument is thisArg which is the context and can used as `this` in the callback
callback.call(scope, array[i], i); // passes back stuff we need
}
};
.Wrapper-blue {
background:#ddd;
margin:5px;
width:60px;
height:60px;
}
<div id="container">
<div class="grid-row">
<div class="Wrapper">
<div class="block"></div>
</div>
<div class="Wrapper">
<div class="block"></div>
</div>
</div>
<div class="grid-row">
<div class="Wrapper">
<div class="block"></div>
</div>
<div class="Wrapper">
<div class="block"></div>
</div>
</div>
</div>
rows[i].childNodes will give you the Wrapper elements inside each grid-row, but then you will have to loop through them, too.
I was not able to get the second loop right as in the first loop I got all the childNodes including the empty text fields. I needed first to run the the for statement and than only filter the ones that has nodeType == 1.
var container = document.getElementById('container');
var rows = container.childNodes;
var rowslenght = container.childNodes.length;
var rowsArray = new Array();
// Get all the grid-row and run through them
for (var a=0; a < rowslenght ; a++) {
// If it is a HTML element than go through
if (gridrow[a].nodeType == 1){
var wpChildren = gridrow[a].childNodes;
var wpChildrenleght = gridrow[a].childNodes.length;
// Run through all the wrappers
for (var b =0; b < wpChildrenleght; b++){
// only get grid-wrapper html
if (wpChildren[b].nodeType == 1){
console.log(wpChildren[b]) // here is your specific div
}
}
}
}
This isn't as hard as you're making it; you don't have to do multiple loops.
The below is supported by all modern browsers, including IE 9+ https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
var container = document.getElementById('container');
var rows = container.getElementsByClassName('grid-row');
// NOTE: this assumes that you only want to get wrappers which are children of grid-rows which are children of a container
var wrapperChildren = [];
rows.forEach(function(row) {
var wrappers = row.getElementsByClassName('Wrapper');
// per comments, adding child count
row['data-child-count'] = wrappers.length;
wrapperChildren.concat(wrappers);
});
It gets easier still if the wrappers are only inside grid-rows already (then you could just select all of them by class name). Working fiddle
EDIT
Per the comment, you want to know how many children each row has, that's easy to add as a data attribute (or any other custom attribute) and then access it after this function has run.
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..