I have a realy hard problem that I couldn't find any solution in Internet
I used document.getElementsByClassName to access one HTML Element by It's class, my element is filterRow of dxDataGrid:
var filterRowElement = document.getElementsByClassName("dx-datagrid-filter-row");
console.log(filterRowElement);
console.log(filterRowElement.length);
My Problem is: The first console.log return HTMLCollection with length = 1 but the second return 0 (I tried to get length to access filterRowElement[0]).
I've tried console.log(filterRowElement[0]) and got undefined too
This is screen shoot:
I don't know why, it is the first time I got this problem
Please give me some advise. Thank you!
THANK YOU, I THINK MY PROBLEM IS DXGRID FILTERROW ELEMENT IS CONSECUTIVELY CHANGE SO I CAN'T ACCESS OLD ELEMENT
UPDATE
I don't know why but Using Jquery save Me (may be not alway true)
setTimeout(function () {
var getfilterRowElement = $(".dx-datagrid-filter-row");
console.log(getfilterRowElement[0]);
}, 3000);
Result:
Thank you so much
Updated: One reason why you might got a 0 for the second line, and a 1 for first line is: you print out filterRowElement.length, and it is true at that time, it was 0. When your event cycle is over, your framework (React, Angular, etc) updated the page (either after your actions or before your actions in the next event cycle). Now console.log prints out the whole structure and when you look at it in the debugger, now it is 1.
In order to solve this problem, I had to do something like this before:
setTimeout(() => {
doSomething();
}, 0);
So now you are waiting for the next event cycle so that your page is "constructed" or "updated".
If it is a static page, I was able to get 1 for both cases and able to access it:
Do you mean
console.log(filterRowElement);
gave you an object with length being 1, and then
console.log(filterRowElement.length);
gave you 0?
The following works:
arr = document.getElementsByClassName("foo-bar");
console.log(arr);
console.log(arr.length);
arr[0].innerHTML = "hello world";
arr[0].style.background = "orange";
arr[0].style.display = "inline-block";
arr[0].style.padding = "1.2em";
arr[0].style.borderRadius = "6px";
<div class="foo-bar"></div>
getElementsByClassName is live... is your page being changed meanwhile? Try document.querySelectorAll(".foo-bar") instead:
arr = document.querySelectorAll(".foo-bar");
console.log(arr);
console.log(arr.length);
arr[0].innerHTML = "hello world";
arr[0].style.background = "orange";
arr[0].style.display = "inline-block";
arr[0].style.padding = "1.2em";
arr[0].style.borderRadius = "6px";
<div class="foo-bar"></div>
Related
const box = document.querySelectorAll(".box");
console.log(box.length);
const direction = [
"top-start",
"bottom-start",
"left-start",
"right-start",
"top-center",
"bottom-center",
"left-center",
"right-center",
"top-end",
"bottom-end",
"left-end",
"right-end"
];
box.forEach((el, index) => {
for (let i = 0; i < direction.length; i++) {
CreateTooltip(el, direction[index], "Hello, World!");
}
});
The above mentioned code rendering 144 tooltips in DOM and I want only 12 with each should have different directions. I don't why this loop is not working! I tried to add forEach loop inside for loop but still the problem is same.
NOTE As some of you asked I pasted my entire code. Hope it will help you and then you will help me. 😅
You can pass in the index of each element like this and get the corresponding value from the direction array
box.forEach((element, index) => {
CreateTooltip(element, direction[index], 'Hello, World!');
})
Your code is working well, as you are iterating over list of boxes and inside that you have another iteration, so the result of your code will always be (number of boxes)*(number of directions) = 144..
So you can Iterate only on boxes or on direction by manipulating one and other lists by there index numbers as given below..
$(box).each(function(i,v){console.log(direction[i])})
If you are using Queryselectorall , if it is class use dot , or if you are using id use #
const box = document.querySelectorAll('.box');
From what you have stated, namely wanting 12 tooltips (same as direction index counts) but getting 144 tooltips (144/12 = 12) you should have 12 elements with .box class in your page. the problem is in your query selection.
const box = document.querySelectorAll('.box');
console.log(box.length); // this should show 12
what you need to do is to set an ID for your element or create a loop for the box (array at this point) and execute your CreateTooltip logic for each of them separately.
Note: I suggest you to test your CreateTooltip in a testing environment (separated file created to test your code) with only one .box element, it's possible that the library you're using does not support multiple calls of CreateTooltip for a single element, that might be the reason you're getting 144 elements instead of 12.
i was wondering how to make a variable go up over time, ive tried to do this -->
var i = 1;
var c = document.getElementById("click");
function workers() {
if (click >= workers*50000)) {
click += -(workers*50000)
click += i++
c.innerHTML = click;
}
}
but it hasnt worked, how do i fix this?
you could do this
let i = 0;
// instead of 2000 insert the frequency of the wanted update (in milliseconds)
const incrementInterval = setInterval(() => i++, 2000)
// when you want it to stop it
clearInterval(incrementInterval)
anyway, i don't really understand how the code supplied with the question has anything to do with it
You have an element and a variable 'click', which tells me you're really not wanting to grow over time per se, but rather grow with every click.
Another difficulty is finding out what you're trying to do with multiplying by 50000. I am assuming you are trying to reset the count after 50000.
One big thing you're missing is the actual association of the click event to your 'click' HTML element. Below, I'm using addEventListener to do that. From there, I'm resetting the counter to '1' if 'i' goes above '5' (I use 5 just to show the reset in a reasonable number of clicks). Then I take the value of 'i' and put it into the innerHTML label of the element that triggered the event.
var i = 1;
document
.getElementById("click")
.addEventListener('click', function(e) {
if (i > 5)
i = 1;
e.target.innerHTML = `click: ${i++}`;
})
<div id='click'>click<div>
Define your question better. What is your goal? What has your code achieved? What result are you getting and how is it different than your expectations? What is 'i' meant to be used for? How does it interact with the function? Why are you multiplying it with 50000? Is workers a separate variable that's globally defined and not shown? Communication is an important skill in this field, and comments are often helpful tools to document your code for others to understand.
I think an alternative answer could be formatted in this way:
let i = 0;
function increment(){
i++;
document.querySelector('h3').textContent = i
}
document.querySelector('button').addEventListener('click',increment)
<button>Click Me</button>
<h3>0</h3>
I've just been trying to make some code to test out tampermonkey stuff on simple maths questions when I came across this error. it would work for the first question, get the question, solve it, enter the answer. The element then changes to a new question however when I use .innerHTML or .textContent it always gives the original question.
Here is my code which shows this:
console.log(document.getElementById('currgamename'))
console.log(document.getElementById('currgamename').textContent)
I get this output:
<span id="currgamename">12-7</span>
6-3 //The first question that appears
Full code:
var delayInMilliseconds = 1000; //1 second
var x = 0
setTimeout(function() {
var handler = setInterval(function() {
document.getElementById('playPadding').childNodes[1].click()
var equation = document.getElementById('currgamename').textContent
var actual = equation.split('-')
var answer = (parseInt(actual[0]) - parseInt(actual[1])).toString()
document.getElementById('currgamename').innerHTML = 'hello'
console.log(document.getElementById('currgamename'))
console.log(document.getElementById('currgamename').textContent)
document.getElementById('gameinput').value = answer
document.getElementById('nextButton').click()
x++;
if (x >= 5) {
clearInterval(handler);
}
}, 1000);
}, delayInMilliseconds);
I have absolutely no clue why it gives the updated element but not the updated text so I could really use some clarification here thanks!
In the console:
>document.querySelector("#currgamename")
<-<span id="currgamename">12-7</span>
>document.querySelector("#currgamename").textContent = "hello"
<-"hello"
------And the HTML on the screen changed to show the "hello" instead of "12-7"------
>document.querySelector("#currgamename").innerHTML = "bye"
<-"bye"
>document.querySelector("#currgamename").innerText
<"bye"
So it works as long as your querySelector is aimed at the correct element it should work
I genuinely cannot believe my stupidity, I've been at this for 4 hours now and the error was that I had document.getElementById('playPadding').childNodes[1].click() inside the setinterval. It was pressing the start button everytime i wanted to answer a new question so it was just replacing it with the old one FML.
I am new to js and hope this is not too trivial, but I am unable to find any help on the net.
I wish to output to console.log and prevent moving to a new line, so the next time the output will be appended to the same line. ie,
"use strict";
for (let i = 0; i<=9;i++){
console.log(i); // here i would like to freeze the output so the result is 0123456789 on one line, rather than those digits in a column.
}
I have seen fixes involving assigning the outputs to a string and printing in 1 hit, but that seems incredibly crude. Even in Fortran 4 as I recall in the '70s, you could prevent moving to a new line before printing again, so I think I am missing something fundamental. Also I cannot find any general help on formatting numerical output in javascript. Can someone point me in the right direction?
Thanks
Unfortunately, the console.log() method will only write out a string to a single line and doesn't support the appending behavior you are looking for.
As you detailed in your original post, you could accomplish writing the final result out through the use of a variable (i.e. displaying the final concatenated string), but not continually appending to the same line within the console itself as the loop is being iterated over.
Alternative Grouping Option
The concept of grouping entries is supported, which is obviously very different than your original ask, but it may be worth considering as mentioned in the documentation for console.group() and might look something like this:
var rollingConcatenation = '';
console.group("Looping Group Example");
for (let i = 0; i<=9;i++){
rollingConcatenation += i;
console.log(rollingConcatenation);
}
console.groupEnd();
This can give your console the following appearance, which can help with readability (depending on your use cases):
Do It Yourself Implementation
Another option might be to store your current console value within a variable and at clear it and rewrite the updated values out. Depending on your very specific use cases, you could achieve the behavior you are looking for using something like this crude implementation:
// Define a custom console
var customConsole = {
// Store a reference to your backing value
tempValue: '',
// Always write out the most recent value
log: function(msg) {
this.tempValue += msg;
console.clear();
console.log(this.tempValue);
},
// A clear method to clear the backing console
clear: function() {
this.tempValue = '';
console.clear();
}
}
for (var i = 0; i < 10; i++) {
// Use your custom console instead of the normal one
customConsole.log(i);
}
Take a new variable outside the loop and then prepare that string inside the loop and then you can console.log() outside the loop.
var str = '';
for (let i = 0; i <= 9; i++) {
str += i;
}
console.log(str);
I've been having problems with my code in JavaScript again. Here is the part of the code that I'm having trouble with and an explanation:
loadThis.onclick = function(){
localStorage.setItem("myName", storedTemporary[i].name);
}
deleteThis.onclick = function(){
this.parentNode.parentNode.remove();
storedTemporary.splice(storedTemporary[i], 1);
}
It splices it from the array and removes it from the screen. But let's say you have 3 items you delete the one and top and the bottom, when you try and load the last one in between it gives an error saying it can't setItem because it "cannot read property undefined". But the interesting thing is that when you console.log the current value of the localStorage item, "myName", it shows the last item's name. This is the for loop. I am using block scoping for it :
var storedTemporary = JSON.parse(localStorage.getItem("temporaryArray"))
for(let i = 0; i < storedTemporary.length; i++)
{
}
I am very confused. Please help.
Thank you,
Scratch Cat