var refreshBtn = document.getElementsByClassName("refresh-button");
var container = document.getElementsByClassName("container");
const maxpalate = 32;
function RefreshFunction() {
for (let i = 0; i < maxpalate; i++) {
let randomhex = Math.floor(Math.random() * 0xffffffff).toString(16);
randomhex = `#${randomhex.padStart(6, "0")}`;
const color = document.createElement("li");
color.classList.add = "color";
color.innerHTML = `<div class="rect-box" style="background: ${randomhex}"></div>
<span class="hex-value">${randomhex}</span>`;
container.appendChild(color);
}
}
I am not getting the solution,please tell me the Solution of this
getElementsByClassName returns multiple elements. You need to use container[0] instead of container.
Call appendChild method instead of appandChild.
First of all, it is not appandChild it is appendChild.
Second "getElementsByClassName" returns an array but the "container" is a single element so you need to use a single element instead.
var container = document.getElementsByClassName("container");
const maxpalate = 2;
function RefreshFunction() {
debugger
for (let i = 0; i < maxpalate; i++) {
let randomhex = Math.floor(Math.random() * 0xffffffff).toString(16);
randomhex = `#${randomhex.padStart(6, "0")}`;
const color = document.createElement("li");
color.classList.add = "color";
color.innerHTML = `<div class="rect-box" style="background: ${randomhex}"></div>
<span class="hex-value">${randomhex}</span>`;
container[0].appendChild(color);
}
}
RefreshFunction()
Related
I cant give a style with js to the starLoc Const
i get this error:
script.js:14 Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at starMove (script.js:14:20)
const btn = document.getElementById('btn');
const star = document.querySelector('.space');
const starLoc = document.querySelectorAll('.star-obj');
var rndLeft = Math.floor(Math.random()*1000);
var rndTop = Math.floor(Math.random()*1000);
function startSpacing(){
btn.style.display = 'none';
starMove();
}
function starMove(){
for(var i = 0; i <= 60; i++){
star.innerHTML += '<div class="star-obj">*</div>';
starLoc[i].style.left = rndLeft + 'px'; //14 line
starLoc[i].style.top = rndTop + 'px';
}
}
<body>
<div class="start">
<button id="btn" onclick="startSpacing()">Start Space Moving</button>
</div>
<div class="space"></div>
<script src="script.js"></script>
</body>
what is wrong with const?
Do not judge strictly, I'm a beginner
First, in your HTML you call startSpacing() while the function name is starMove(). Second, you dynamically generate elements, so you need to get them every time the function is called. This means moving starLoc to the function. See the example with color: red;
const star = document.querySelector('.space');
let rndLeft = Math.floor(Math.random() * 1000);
let rndTop = Math.floor(Math.random() * 1000);
function starMove() {
for (let i = 0; i <= 60; i++) {
star.innerHTML += '<div class="star-obj">*</div>';
let starLoc = document.querySelectorAll('.star-obj');
starLoc[i].style.color = 'red';
}
}
<div class="start">
<button id="btn" onclick="starMove()">Start Space Moving</button>
</div>
<div class="space"></div>
You can use document.getElementsByClassName to get a live HTMLCollection of elements.
const starLoc = document.getElementsByClassName('star-obj');
However, you should really use document.createElement in the loop instead.
for (let i = 0; i <= 60; i++) {
const div = document.createElement('div');
div.textContent = '*';
div.style.left = rndLeft + 'px';
div.style.top = rndTop + 'px';
star.append(div);
}
function showMovies (dataMovie) {
const main = document.getElementById('main');
main.innerHTML = '';
for (let i = 0; i < dataMovie.length; i++) {
const newMovie = document.createElement('div');
newMovie.innerHTML =
`<div class="movie-img">
<img src="${url_poster + dataMovie[i].poster_path}" alt="${dataMovie[i].title}-poster">
</div>
<div class="movie-info">
<h3>${dataMovie[i].title}</h3>
<div class="genres">
</div>
<p>${dataMovie[i].release_date}</p>
</div>
<div class="movie-overview">
<h3>Synopsis:</h3><br>
<p>${dataMovie[i].overview}</p>
</div>`
main.appendChild(newMovie);
for (let j = 0; j < genresList.length; j++) {
dataMovie[i].genre_ids.forEach(id => {
if (genresList[j].id === id) {
let g = '';
const div = document.querySelector('.genres');
const p = document.createElement('p');
g += genresList[j].name;
p.innerHTML = `<p>- ${g} </p>`
div.appendChild(p);
}
});
}
}
I want to display all genres of one movie.
When i get one movie i've got no problem, when i get more than one, the first takes all the genres and no genres are displayed for the others.
movieData is my data.results of the api (tmdb).
You are selecting the same .genres all the time.
Try this please:
const div = newMovie.querySelector('.genres');
function showMovies(dataMovie) {
const main = document.getElementById('main');
main.innerHTML = '';
for (let i = 0; i < dataMovie.length; i++) {
const newMovie = document.createElement('div');
newMovie.innerHTML =
`<div class="movie-img">
<img src="{url_poster + dataMovie[i].poster_path}" alt="{dataMovie[i].title}-poster">
</div>
<div class="movie-info">
<h3>{dataMovie[i].title}</h3>
<div class="genres">
</div>
<p>{dataMovie[i].release_date}</p>
</div>
<div class="movie-overview">
<h3>Synopsis:</h3><br>
<p>{dataMovie[i].overview}</p>
</div>`
main.appendChild(newMovie);
for (let j = 0; j < genresList.length; j++) {
dataMovie[i].genre_ids.forEach(id => {
if (genresList[j] === id) {
let g = '';
const div = newMovie.querySelector('.genres');
const p = document.createElement('p');
g += genresList[j].name;
p.innerHTML = `<p>- ${g} </p>`
div.appendChild(p);
}
});
}
}
}
var genresList = [1,2,3,4,5,6,7,8]
showMovies([{genre_ids:[1,2,3]},{genre_ids:[4,5,6]}])
<div id="main"></div>
The problem is that when you write const div = document.querySelector('.genres'); you are always selecting the first element on the page that matches the selector.
One idea would be to add an id to the movie container, which you can then use on your query.
For instance something like this:
when you create the container div:
const newMovie = document.createElement('div');
newMovie.classList.add('new-movie');
newMovie.setAttribute('movie-id', dataMovie[i].id);
then on your selector:
const div = document.querySelector(`.new-movie[movie-id="${dataMovie[i].id}"] .genres`);
This would give you the .genres div inside the correct container (instead of the first one on the page).
For a different approach you could also try to use
const div = newMovie.querySelector('.genres');
instead of
const div = document.querySelector('.genres');
Which should give you the same result
I have degrees in Celsius switched them to Fahrenheit and cannot write them back to page.. picked them up with this statement
temp = document.querySelectorAll(".mylist span");
x=[]
for (let i = 0; i < temp.length; i++) {
temp[i].style.backgroundColor = "red";
x[i] = Number(temp[i].innerHTML);
Cannot write them back same way... Does not work
You need to set the innerHTML/textContent of the element with the new value.
const spans = document.querySelectorAll('#mylist span');
function CToF(v) {
return v * 9/5 + 32;
}
setTimeout(() => {
spans.forEach(span => {
const { textContent } = span;
span.classList.add('red');
span.textContent = CToF(textContent);
});
}, 2000);
.red { color: red; }
<div id="mylist">
<span>10</span>
<span>40</span>
<span>90</span>
</div>
I have this piece of javascript and I need every element "title" to be colored with different randomized color. I accomplished colorize only the first one. It is possible? Thanks
var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById('title').style.color = randomColor;
<div id="title"><a>TEXT1</a></div>...<div id="title"><a>TEXT2</a></div>...
Just invoke changeColor(); functions.
$(function(){
changeColor();
});
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerText;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = ""
for(var j = 0; j < innerTextSplit.length; j++) {
var randomColor =getRandomColor();
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
paragraphs[i].innerHTML += innerTextSplit[j];
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
As I already commented, you cannot use duplicate IDs, prefer using a class instead and modify your code accordingly.
var getElm = document.getElementsByClassName('title');
for(var i = 0, l = getElm.length; i < l; i++) {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
getElm[i].style.color = '#' + randomColor;
}
<div class="title"><a>TEXT1</a></div>
<div class="title"><a>TEXT2</a></div>
Some explanation of how the above code works:
I am using getElementsByClassName which will return me an array of elements you want to target, in this case, it's the ones with the class name of title. Then I loop them, generate a new random hex, and assign it to the looped element.
Make sure you don't forget to concatenate your hexcode with #
Use like this .without classname
using document.querySelectorAll().it will select the element.
Then applied each element with color using Array#forEach
And you are missing # in dom for adding color
document.querySelectorAll("div[id='title']").forEach(function(a){
var randomColor = Math.floor(Math.random()*16777215).toString(16);
a.style.color ='#'+randomColor;
})
<div id="title"><a>TEXT1</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>...
HTML
<div class="title"><a>TEXT1</a></div>...
<div class="title"><a>TEXT2</a></div>...
JS
var elements = document.getElementsByClassName('title');
var usedColors = {};
var getRandomColor = function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
while(usedColors[randomColor] === 1) {
randomColor = Math.floor(Math.random()*16777215).toString(16);
}
usedColors[randomColor] = 1;
return randomColor;
};
for (var i = 0; i < elements.length; i++ ) {
var randomColor = getRandomColor();
elements[i].style.color = "#"+randomColor;
}
JSFIDDLE
https://jsfiddle.net/1cuwdLye/
I would like to create several divs with the same options like color, width, height, etc.
I would like to add all of these divs to an array, but I need to do this dynamically.
My current code:
var ArrayInfo = [];
do {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
}while(i < x);
x can be a very very large number.
Is this the right way to add div a to an array?
How can I write text into the elements of an array?
I tried this:
ArrayInfo[i].innerHTML = "something";
But it didn't work.
You never increment i, so your loop will never end.
Second, you never actually add any of the divs to the document -- creating them doesn't do that for you.
And as noted in the comments, you can't use the same id over and over.
var ArrayInfo = [];
var x = 10;
var ctr = document.getElementById('ctr');
for (var i = 0; i < x; ++i) {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div' + i;
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
ctr.appendChild(InfoDiv);
}
for (i = 0; i < x; ++i) {
ArrayInfo[i].innerHTML = "div " + i;
}
<div id=ctr></div>
I'd avoid using do...while. I'd also avoid creating a new div on every loop. Instantiate once, then clone (it's faster).
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
var ArrayInfo = [];
for(var i = 0; i < x; i++) {
var div = InfoDiv.cloneNode(true);
div.id += i; // Add number to id
ArrayInfo.push(div);
}
IDs must be unique! Considering adding a number to the end of each Info_Div to uniquely identify it.
Also consider using a for loop instead of a do while loop.
The convention for JavaScript variables is lowerCamelCase. So we should fix that as well.
In your code, the divs were added to the array but not to the document. If you wanted to add them to the DOM, you would have to add document.body.appendChild.
Your code would look more like this.
var arrayInfo = [];
var x = 5; // Or whatever value it is
for (var i = 1; i < x; i++) {
var infoDiv = document.createElement('div');
infoDiv.id = 'Info_Div' + i;
infoDiv.className = 'Info_Div';
infoDiv.style.width = "100px";
infoDiv.style.height = "30px";
infoDiv.style.display = "inline-block";
arrayInfo.push(infoDiv);
arrayInfo[i].innerHTML = "div " + i;
document.body.appendChild(infoDiv);
}