Javascript get dynamically set data-* attribute [duplicate] - javascript

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

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 onclick attachment indexer issue [duplicate]

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++;
}
}
}

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);
}

For cycle or for each with js objects

I got a problem to add a onclick event to object who can be many times in same page
I am trying to
var i;
for (i = 1; i<=10; i++) {
var tmpObj='lov_DgId_D_'+i;
var tmpObj2=tmpObj.getElementsByTagName('a')[0];
if (tmpObj2 != null) {
tmpObj2.onclick= DgIdOnClick;
}
}
But got a error TypeError:
Object lov_DgId_D_1 has no method 'getElementsByTagName' , but this is working
lov_DgId_D_2.getElementsByTagName('a')[0].onclick= DgIdOnClick;
This ibject lov_DgId_D_ can be from 1 like lov_DgId_D_1 or lov_DgId_D_99 u.t.c
What wil be the best solution to add onclick to all lov_DgId_D_* objects ?
As you use jquery, the simplest is
for (i = 1; i<=10; i++) {
$('#lov_DgId_D_'+ i+ ' a').click(DgIdOnClick);
}
If you want to bind your event handler to all a elements inside elements whose id starts with lov_DgId_D_, then it's as simple as
$('[id^="lov_DgId_D_"] a').click(DgIdOnClick);
The problem you have is a confusion between the id of an element and the actual element. Some code that should work for you is this one:
var i;
for (i = 1; i<=10; i++) {
var tmpObj=document.getElementById('lov_DgId_D_'+i); // <-- here
var tmpObj2=tmpObj.getElementsByTagName('a')[0];
if (tmpObj2 != null) {
tmpObj2.onclick= DgIdOnClick;
}
}
Slightly easier to read code:
for (var i=0; i<=10; i++) {
var anchor = document.querySelector('#lov_DgId_D_'+i + ' a');
if (anchor) anchor.onclick = DgIdOnClick;
}
A note: this code attaches a click event to the first anchor (a element) inside each element with the id lov_DgId_D_n, with n being 1->10. Your original code seems to want to do the same thing.
Another note: usually when you iterate over elements using their id's to identify them, you are better suited to add a class to those elements instead. It provides for more maintaintable code and probably easier to understand as well.

How to have every attribute's names and values of an element? [duplicate]

This question already has answers here:
Get all attributes of an element using jQuery
(8 answers)
Closed 8 years ago.
I'm trying to have every attribute's names and values of an element of the DOM using jQuery and JavaScript. I've written this piece of code:
$.each(attribute.attributes, function (ident, attrib) {
alert(attrib.value);
alert(attrib.name);
});
"attribute" is an attribute of the DOM.
I've found .attributes method online but I don't know why the program crashes entering in this function.
$('.obj').each(function() {
var attArray = [];
for(var k = 0; k < this.attributes.length; k++) {
var attr = this.attributes[k];
if(attr.name != 'class')
attArray.push(attr.value);
}
alert(attArray[2]); //x = 55
//do something with attArray here...
});
http://jsfiddle.net/tjuFH/3/
Source
Credits
JavaScript
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});

Categories