Javascript onclick attachment indexer issue [duplicate] - javascript

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 6 years ago.
I have problem with the following 'registerHandlers' javascript function. When I am trying to attach the onclick even, it always displaying '3'. Here how it should work;
An alert should display anchor's zero-based index within a document instead of following the link.
For example, in the document below, the alert should display "2" when Google anchor is clicked since it is the third anchor element in the document and its zero-based index is 2.
Here the script and test page in JSFiddle
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}

This should work :)
function registerHandlers() {
var as = document.getElementsByTagName('a');
var j = 1;
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
alert(j);
j++;
}
}
}

Related

Javascript to change color of all spans with certain ID [duplicate]

This question already has answers here:
Mulitple Elements with the same ID
(5 answers)
Closed 2 years ago.
I have the following code to change the color of text with a certain spanID. Currently, it only changes the first instance of the span and on subsequent instances. Any suggestions?
<script>
function spanColor() {
var x = document.getElementById('someId');
x.style.color = '#'+Math.random().toString(16).substr(-6);
}
</script>
If you want to return all the needed elements you should use querySelectorAll(#id)
But as you saw in the comments - ID is not the best way to get more than one item.
You should change the ID for a ClassName and use var x = document.getElementsByClassName("example");
So your code should look like this:
<script>
function spanColor() {
var x = document.getElementsByClassName('someClassname');
var i;
for (i = 0; i < x.length; i++) {
x[i].style.color = '#'+Math.random().toString(16).substr(-6);
}
}
</script>

javascript - extracting cell value [duplicate]

This question already has answers here:
JavaScript, getting value of a td with id name
(8 answers)
Closed 2 years ago.
I wrote some code that is scanning my HTML table, and I want to use it for formatting that table.
var count_rows = document.getElementById("currency_tab").rows.length;
for (i = 0; i <= count_rows; i++ ) {
var count_cells = document.getElementById("currency_tab").rows[i].cells.length;
for (j = 0; j <= count_cells; j++) {
var check_str = document.getElementById("currency_tab").rows[i].cells[j];
/*
console.log(check_str);
console.log(typeof(check_str));
*/
var check = check_str.includes("-")
if(check) {
check_str.style.color = "red";
} else {
check_str.style.color = "green";
}
}
}
js console.log(check_str); is returning not a value of cell but an object e.g. <th>CURRENCY</th>.
I have tried to parse it with check_str.slice but that is forcing me to count a length of chars in object. I hope there is easier method to resolve that.
You can get the text with check_str.textContent
Please refer to the following documentation: Node.textContent
Also, if you are unsure about the properties of an object you can log them with console.dir(check_str).

Why does this javascript for loop cause an early exit? [duplicate]

This question already has an answer here:
(infinite?) loop in javascript code
(1 answer)
Closed 5 years ago.
Right now I am really stumped. I have a short function, called "validate", and for some reason the for loop I have prevents an outer for loop from running.
Here it is breaking by only printing out the first entry:
function validate(str) {
for(i=0; i<str.length; i++) {
// do nothing
}
return str;
}
And here's the version that works:
function validate(str) {
/*for(i=0; i<str.length; i++) {
// do nothing
}*/
return str;
}
Here is my fiddle.
Here is the sample text file.
Try encapsulating your variable i. var i = 0;
function validate(str) {
for(var i = 0; i < str.length; i++) {
// do nothing
}
return str;
}
Without the var you are adding it to the global scope or the window object

Adding class to div with onclick function [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I tried to find some way to solve my problem, which is to add class to the divs when I click on them, but I can't make it work.
var el = document.getElementsByClassName('applications');
var i;
for (i = 0; i < el.length; i++) {
el[i].addEventListener("click", function() {
if (el[i]) {
el[i].className += el[i].className ? ' openDiv' : 'openDiv';
}
});
}
I have the 'for loop' because I used getElementsByClassName which gives a node list. I also created a codepen example:
http://codepen.io/anon/pen/dGqmMy
Instead of using complex string manipulation, use classList:
el[i].classList.add('openDiv');
I believe you might need to add a closure for the eventListeners to work.
So this would be considered as a solution:
var el = document.getElementsByClassName('applications');
var i;
for (i = 0; i < el.length; i++) {
(function (i) {
el[i].addEventListener("click", function() {
if (el[i]) {
el[i].classList.add('openDiv');
}
});
})(i);
}

Javascript get dynamically set data-* attribute [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
Let's say I have multiple elements with the class game_join_a, with their respective data-tbl attributes set dynamically from a database. I want to retrieve those atrributes to further use them in my code.
The code I'm using below returns tells me that a[i] is undefined.
a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++){
a[i].addEventListener("click", function(){
console.log(a[i].getAttribute("data-tbl"));
});
}
a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++){
a[i].addEventListener("click", function(){
console.log(this.getAttribute("data-tbl"));
});
}
this refers to the element that the click event is binded to. If you're dynamically adding the elements rather than just the data- attributes, you could also try this:
var a = document.getElementById('game_join_container'); // just something that contains all the elements that will be dynamically added
a.addEventListener('click', function (event) {
// check to see if original element clicked is a "game_join_a" element first
if(event.target.classList.contains('game_join_a')) {
console.log(event.target.getAttribute('data-tbl'));
}
});
Try this
var a = document.getElementsByClassName("game_join_a");
for(i = 0; i < a.length; i++) {
a[i].addEventListener("click", function (e) {
console.log(e.currentTarget.getAttribute("data-tbl"));
}, false);
}
Example

Categories