Im supposed to make 8 boxes and style them each, make the boxes with for loop. Every odd box should look different then the others. I have tried to make an id, but when i use the id in CSS, it wont do anything. Can someone help?
Here is the code i have:
var text = "";
var i;
for (i = 1; i < 10; i++) {
text += "Box number " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
.demo {
border: black;
}
<p id="demo"></p>
As volodymyr says use css nth-child property.
In javascript you can accomplish this in the following manner:
for(let i = 0; i < document.querySelectorAll('.class').length; i += 2){
document.querySelectorAll('.class')[i].style.color = 'red';
}
<div class="class">1</div>
<div class="class">2</div>
<div class="class">3</div>
<div class="class">4</div>
<div class="class">5</div>
<div class="class">6</div>
<div class="class">7</div>
<div class="class">8</div>
<div class="class">9</div>
<div class="class">10</div>
This uses a for loop which iterates over every odd element, and then applies styles via javascript. Usually a pure CSS implementation would be preferable though.
You can use css nth-clild property
.class:nth-child(odd) {background: red}
<div class="class">1</div>
<div class="class">2</div>
<div class="class">3</div>
<div class="class">4</div>
<div class="class">5</div>
<div class="class">6</div>
<div class="class">7</div>
<div class="class">8</div>
<div class="class">9</div>
<div class="class">10</div>
Your css references the "class" demo selector but your HTML uses an "id" property id='demo'. Change either one to match the other.
Related
In this websites the user can add as much boxes as he wants, and every box contains a green and blue small boxes, the user should be able to click the blue box to remove the green box. the issue is that every time I click the blue box it doesn't remove the green box unless there is only one parent box is made. I have tried a lot of ways but nothing is working.
let count = 0;
function addBox() {
let box = `
<div class="box">
<div class="lbox" id="lbox">
</div>
<div class="rbox" id="rbox">
</div>
<h1>
${count}
</h1>
</div>
`
$(`#boxes`).append(box);
document.getElementById("lbox").addEventListener("click", function() {
rbox.remove();
})
count++;
}
If you have more than one parent box you need to iterate over each one.
You need to do something like;
let boxes = document.querySelectorAll('.box');
boxes.forEach(function(box){
box.querySelector('lbox').addEventListener('click',function(){
box.remove();
});
})
I haven't tested this, but the key part is the forEach function. This means everything you do inside the function is scoped to that box.
id must, at all times, be unique per-document. Learn about this very basic here: https://www.w3schools.com/hTML/html_id.asp. Your code keeps readding the same id values over and over, making your HTML invalid and your code dysfunctional.
Here's a working code example that doesn't rely on ids to get the job done:
let count = 0;
function addBox() {
let box = document.createElement('div');
box.className = 'box';
box.innerHTML = `
<div class="lbox">
</div>
<div class="rbox">
</div>
<h1>
${count}
</h1>`;
document.getElementById('boxes').appendChild(box);
box.querySelector('.lbox').addEventListener('click', function() {
box.querySelector('.rbox').remove();
})
count++;
}
.lbox, .rbox {
display: inline-block;
height: 40px;
width: 40px;
}
.lbox { background-color: blue; }
.rbox { background-color: green; }
<button onclick="addBox()">Add Box</button>
<div id="boxes"></div>
you need to define to delete the other box inside the same parent div.
I would delete the id because the defenition in class is the same.
I would also change the class names to something, wich makes visible what the green and what the blue box is.
You can do following:
let count = 0;
function addBox() {
let box = `
<div class="box_wrapper">
<div class="blue_box">
</div>
<div class="green_box">
</div>
<h1>
${count}
</h1>
</div>
`
$(`#boxes`).append(box);
$( ".blue_box" ).click(function() {
$(this).parent().find(".green_box").remove();
});
count++;
}
I think document.getElementById will always select the first element only with the given id. Therefore only the first lbox element in the dom keeps getting more and more eventlisteners attached to it, while the others won't get any. Make the id's of your elements unique by appending the count. That will make sure that every element gets it's eventlistener:
let count = 0;
function addBox() {
let box = `
<div class="box">
<div class="lbox" id="lbox${count}">
</div>
<div class="rbox" id="rbox${count}">
</div>
<h1>
${count}
</h1>
</div>
`;
$(`#boxes`).append(box);
document.getElementById("lbox" + count).addEventListener("click", function() {
$(".rbox" + count).remove();
})
count++;
}
I'm trying to find out if it's possible to clone an HTML div with JS, edit it and append it again as a new element. So my source is, for example, this code here:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
After copying this element, I need to find a way to change the attribute id of the new cloned input, clear the input value and paste it again in the wrapper so that it looks like this at the end:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
<div class="element">
<input id="test--2" value=""/>
</div>
</div>
Does that make sense to you? If yes, how can I get this done? Or is it better to assign the content to a variable to append it? I'm looking for the best way here and maybe my idea is a solution too.
You can use pure JavaScript to do this by just cloning the .element div using the cloneNode() method, assign new id and value to the clone div and finally append it back to the document using the insertBefore() method like this:
let x = document.querySelector(".element");
let y = x.cloneNode(true);
y.children[0].id = "test--2";
y.children[0].defaultValue = "";
x.parentNode.insertBefore(y, x.nextSibling);
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
JSFiddle with the above code: https://jsfiddle.net/AndrewL64/jvc7reza/18/
Based on this answer you could do like:
$('#cloneBtn').on('click', function() {
// get the last input having ID starting with test--
var $inp = $('[id^="test--"]:last'); // Or use :first if you need
// Get parent element
var $div = $inp.closest('.element');
// Create clone
var $div_clone = $div.clone();
// Retrieve number from ID and increment it
var num = parseInt($inp.prop("id").match(/\d+/g), 10) + 1;
// Generate new number and assign to input
$div_clone.find('[id^="test--"]').prop({id: 'test--' + num, value: ''});
// Insert cloned element
$div.after($div_clone); // Or use .before() if you need
});
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Scrambled elements, retrieve highest ID, increment, clone, append.
If your numbered IDs are scrambled, we first need a way to retrieve the highest ID number. Here's an implementation in pure JavaScript:
function cloneElement () {
const inpAll = document.querySelectorAll('[id^="test--"]');
if (!inpAll.length) return; // do nothing if no elements to clone
const maxID = Math.max.apply(Math, [...inpAll].map(el => +el.id.match(/\d+$/g)[0]));
const incID = maxID + 1;
const element = document.querySelector('.element'); // Get one for cloning
const eleClone = element.cloneNode(true);
const inpClone = eleClone.querySelector('[id^="test--"]');
inpClone.id = 'test--'+ incID;
inpClone.value = incID; // just for test. Use "" instead
document.querySelector('.wrapper').prepend(eleClone);
}
document.querySelector('#cloneBtn').addEventListener('click', cloneElement);
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="1" />
</div>
<div class="element">
<input id="test--23" value="23" />
</div>
<div class="element">
<input id="test--7" value="7" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I don't know what data you know, why you want to do such a thing but it can be done :-)
One way is like that:
const elemToCopy = document.getElementById("test--1").parentNode; // I assume you know id
const copiedElem = elemToCopy.cloneNode(true);
const newInput = copiedElem.querySelector("#test--1");
newInput.id = "test--2";
newInput.value = "";
elemToCopy.parentNode.append(copiedElem);
Let me know in a comment if something is not clear :-)
Yes, use jQuery's .clone().
Here is an example that might be relevant to your situation:
let newElement = $('.element').clone();
newElement.find('input').attr('id', 'test--2').val('');
$('.wrapper').append(newElement);
Explanation
In the first line, we created a new cloned element by using jQuery clone().
Then, we found it's child input, changed it's ID and reset the val().
Finally, we found the .wrapper element and appended the new cloned element to it.
This question already has answers here:
How to apply CSS style to all elements with same ID using one button?
(6 answers)
Closed 6 years ago.
I want to use getElementById("xxx").style.color = "xxx".
With this I want to change some css value. But the problem is when i use this and test all same id with this but it does't effect all id and effects only the first one.
Sample code is as follow:
<html>
<body>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<script>
document.getElementById("test").style.color = "blue"
</script>
</body>
</html>
What should i do to change all 4 Test to color blue.
AnyIdea pls.
Thanks
An ID must be unique in an HTML document. Write valid HTML.
To represent multiple, related elements: use a class.
You can then use getElementsByClassName or querySelectorAll to get an array-like object which you can use a for loop to access each element in turn.
var elements = document.querySelectorAll(".test");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
}
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
Alternatively, write a stylesheet with a descendant combinator and toggle the classes on a containing element.
document.getElementById("container").classList.add("foo");
.test { color: black; }
.foo .test { color: blue; }
<div id="container">
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
</div>
As stated before, an ID must be unique. If you want to give multiple DOM-elements the same style just use 'class'.
you could try this:
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
var divList = document.getElementsByClassName("test");
for (var i = 0; i < divList.length; i++) {
divList[i].style.color = "red";
}
</script>
</body>
</html>
to change the style using javascript.
There are two problems with your code :
id must be unique, so you should use eg. class instead
you should loop across the different elements that are selected
This is my prefered way to correct those two problems :
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
Array.prototype.slice.call(
document.getElementsByClassName("test")
).forEach(function(element) {
element.style.color = "blue"
});
</script>
</body>
</html>
See also this Fiddle.
For jQuery Solution
You cannot use same id for performing same operation on all the elements
You can use class name and add style using jquery like
$(".className").css("color","blue");
html
<div name="hhh" class="col-sm-7 new" align="left" >
</div>
javascript
yes.onclick =function()
{
var all = document.getElementsByName("hhh");
for(var i = 0, max = all.length; i < max; i++)
{
all[i].innerHTML="You have clicked Yes.";
}
}
no.onclick =function()
{
var all = document.getElementsByName("hhh");
for(var i = 0, max = all.length; i < max; i++)
{
all[i].innerHTML="You have clicked No.";
}
}
Here in html two buttons are there yes and no.If the user clicks yes,yes.onclick() will execute and if user clicks no,no.onclick() will execute.
In the same division hhh, i have to display the message according to click. But if i write the above code,the message is displayed even before the click.
It is considering hhh as only one name. how can i edit the code, so that it will display message according to the click? Right now it is over writing the existing message.I dont want to over write.I want to display the previous message also.
u should use getElementsByTagName() or better u should use getElementById if you have only one div.
Where do you assign name "yes" and "no" to a js var? maybe the problem is that.
if there are no reason to assign function dinamically by code you can also define only one function
function myError(e){
var all = document.getElementsByTagName("hhh");
for(var i = 0, max = all.length; i < max; i++)
{
all[i].innerHTML="You have clicked " + e.value;
}
}
then assign function to ur button
<input type="button" value="yes/no" onClick="myError(this)">
There are many ways to handle click events in javascript. It seems like you are trying to design a button UI. You should not have to parse an array of elements, chose a better selector. Also there is no name attribute for div elements in HTML, your all array is null.
One way to do it is shown below.
https://jsfiddle.net/699ddkvk/
<div id="hi" style="background-color: red; width:50px; height:50px;" align="left" ></div>
<br>
<div id="ho" style="background-color: blue; width:50px; height:50px;" align="left" ></div>
red = document.getElementById("hi");
blue = document.getElementById("ho");
red.onclick=function(){
red.innerHTML="YES";
};
blue.onclick=function(){
blue.innerHTML="YES";
};
<div name="hhhYest" class="col-sm-7" onClick="clickEvent('yes')" new" align="left" >
</div>
<div name="hhhNo" class="col-sm-7" onClick="clickEvent('no')" new" align="left" ></div>
function clickEvent(yesOrNo)
{
//your logic here yesOrNo
}
all[i].innerHTML = ...
all[i].innerHTML += "\n" + ...
And don't fiorget to set
white-space: pre-line;
in css.
I am trying to get text to showup after each post in my Tumblr theme, and the javascript works in the jsfiddle, but not when I include it into the theme. Am I missing something?
http://jsfiddle.net/KP3uw/70/
HTML
<div id="wrapper">
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div id="counter"></div>
</div>
JAVSCRIPT
/*global */
function statwrap() {
var count;
var counter;
var bob;
count = document.getElementsByTagName('div').length;
counter = document.getElementById('counter').innerHTML = count;
bob = document.getElementsByClassName('stat-wrap');
var i;
for (i = 0; i < counter; i++) {
bob[i].innerHTML = "jkfdgdff14";
}
}
window.onload = statwrap();
Here's my tumblr theme I have pasted the javascript into btw. (http://lgbtvee.tumblr.com/) I've tried both just above </head> and </body> ending tags but it didn't work either place.
I think you have made this wayy to complicated.
Try using jQuery and using the append() function:
$( ".stat-wrap" ).append( "<p>Test</p>" );
Example:
http://jsfiddle.net/KP3uw/74/
maybe it's not exactly answer to your question but you can add some content to all elements with css :after.
.stat-wrap:after {
content: "jkfdgdff14";
display: block;
}
demo: http://jsfiddle.net/t0ro94dz/
I would have made this a comment, but don't have enough reputation to do it yet.
Your loop's condition i < counter is off, I think. The variable counter is tied to innerHTML, which I believe is a string (not a number). Try changing it to i < count.
--edit--
I also noticed that your theme is throwing 2 of the same errors:
Uncaught TypeError: Cannot set property 'innerHTML' of null
since you don't actually have any elements with the ID of counter on the page. Also, in the page source, your script is repeated twice.
I dont know what is not working but there are so many divs. Maybe you want limit and say
count = document.getElementsByClassName('post').length;
Also can you check if you need to parse innerHTML into int using parseInt, some JS compilers can scream
document.getElementById('counter').innerHTML = count;
count = parseInt(document.getElementById('counter').innerHTML);
OR simply
document.getElementById('counter').innerHTML = count
counter = count