I'm trying append to the next element of multiple divs. So far I have this:
HTML
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
After the function runs, the content should look like this:
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
This is my function thus far:
var blue = document.querySelectorAll("[data-color='blue']");
var next = blue.nextSibling;
for (var i=blue.length; i--;) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].parentNode.appendChild(insertdiv, blue[i]);
}
Can't get this to work properly though.
No jQuery please.
querySelectorAll returns a list of elements. That list doesn't have a nextSibling property, so your second line gives you undefined in next.
var blues, i, insertDiv;
blues = document.querySelectorAll("[data-color='blue']");
for (i = 0; i < blues.length; ++i) {
if (blues[i].nextSibling) {
console.log(blues[i].nextElementSibling.tagName);
insertDiv = document.createElement('p');
insertDiv.className = 'content';
insertDiv.textContent = 'My Content';
blues[i].nextElementSibling.appendChild(insertDiv);
}
}
There as several logical errors in your code. #T.J. Crowder has described them perfectly.
However, in your case I would rather use CSS next sibling selector in querySelectorAll:
var next = document.querySelectorAll("[data-color='blue'] + *");
for (var i = 0, len = next.length; i < len; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].appendChild(insertdiv);
}
DEMO: http://jsfiddle.net/8uywP/
Why don't you just add them to the .yellow divs? Like this:
var yellow = document.getElementsByClassName("yellow");
for (var i=0, l = yellow.length; i<l; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
yellow[i].appendChild(insertdiv);
}
Working Fiddle example
There is no need to "Traverse" the dom like that if you have a class available on the elements you need.
Related
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>
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
}
var wtc = document.getElementById("sw").value;
var cw = wtc.split("").join(' ');
cw.toString();
var x=document.getElementById("demo");
x.innerHTML=cw;
I have this code. how can i add id to the splitted(am i right on my term??) word.. it is possible?
I want is to add id on each letter that is splited. I dont know the exact number of letter because it's depend on the user's inputted word.
for example. i have this word from split.
[W][O][R][M]
i want it to be something it this. or anything that have an id :)
<div id="DIVtext1">W</div>
<div id="DIVtext2">O</div>
<div id="DIVtext3">R</div>
<div id="DIVtext4">M</div>
Thanks!
do you mean something like:
var word = "WORM".split("");
var demoEle = document.getElementById("demo");
for(var w = 0, len = word.length; w < len; w++) {
var divEle = document.createElement("div");
divEle.id = "DIVtext"+(w+1);
divEle.onclick = (function(v) {
return function() { copyDiv( "DIVtext" + (v+1) ) };
})(w);
divEle.innerHTML = word[w];
demoEle.appendChild( divEle );
}
Demo: jsFiddle
Updated Demo:: jsFiddle Updated
You could use a loop (for(i=0;i<splittedArray;i++)) and jQuery to add div tags to the dom with the innerHtml being the word.
Basically, once you have it in your array you can put it wherever you want. I find that jQuery makes it easy; however, you could also do it through jscript alone.
This can be achieved pretty easily using jQuery.
var letters = $('#sw').val().split('');
$.each(letters, function(i, letter) {
$('<div />', {
id: 'DIVtext'+ i,
text: letter
}).appendTo('#demo');
});
JSFiddle
If jQuery isn't an option, here's what you can do with vanilla JS.
var letters = document.getElementById('sw').value.split(''),
demo = document.getElementById('demo');
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('div');
letter.innerHTML = letters[i];
letter.id = 'DIVtext'+ i;
demo.appendChild(letter);
}
JSFiddle
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)
}
I have variable x that contains set of attributes.
var x = 'class="test test1 test2" id="xyz" style="color:red"';
How can i insert x to the <body> tag. so body looks like
<body class="test test1 test2" id="xyz" style="color:red">
you could create a temp element and att attributes to it and then append all of its attributes to the body:
var x = 'class="test test1 test2" id="xyz" style="color:red"',
temp = $("<b "+x+">")[0],
attr = {};
for (var i=0, attrs=temp.attributes, l=attrs.length; i<l; i++){
attr[attrs.item(i).nodeName] = attrs.item(i).value;
}
$("body").attr(attr);
demo: http://jsbin.com/udilib/edit#javascript,html,live
but if you can then make the class, id and style as an object instead of a string, will save some code for you.
This probably isn't bullet-proof, but it seems to handle your example input fine:
var x = 'class="test test1 test2" id="xyz" style="color:red"',
pairs = x.match(/\w+\=\"[^\"]+\"/g),
$body = $('body');
for (var i = 0, len = pairs.length; i < len; i++) {
var parts = pairs[i].split('='),
attrName = parts[0],
attrValue = parts[1].replace(/\"/g, '');
$body.attr(attrName, attrValue);
}