So I have a Javscript that can retrieve the id from onClick, but it only selects the first div with an id. The problem is that I have multiple unique id's that are generated in php and then saved in mysql database. The id's are unique but I need my onClick to retrieve the id in the div block.
function postFunction() {
var i;
var x;
for (i = 0; i< x.length; i++)
x = document.getElementsByClassName("post")[0].getAttribute("id");
//alert(this.id);
alert(x);
}
Is there a way to select id per code block?
I see you have the jQuery tag in your question. Try this:
function postFunction() {
var ids = []; //in case you need to have all ids;
$('.post').each(function() {
var id = $(this).attr('id');
ids.push(id); //Store the id in the array
alert(id);
});
console.log(ids); //Show all ids.
}
Using Jquery will make life easier.
var h=[];
$("div").each(function(){
h.push($(this).attr('id'));
});
alert(h); You will get a array of all div ID's.
Without jQuery:
function postFunction() {
var ids = Array.prototype.map.call(document.getElementsByClassName("post"), function(elem) {
return elem.id
});
console.log(ids.join(", "));
}
You need to get the elements, and then loop over them (currently your loop code doesn't do anything)
function postFunction() {
var postEls = document.getElementsByClassName('post'),
postElsCount = postEls.length;
for (var i = 0; i < postElsCount; i++) {
alert(postEls[i].id);
}
}
jQuery will always ease such operations but you can also achieve the same using vanilla javascript. It takes effort & time because of cross browser support for javascript varies much but it's worth to give a try.
function postFunction() {
var ids = [];
var x = document.getElementByClassName('post');
for (var i = 0; i < x.length; i++) {
var temp = x[i].getAttribute("id");
ids.push(temp);
}
console.log(ids)
}
getElementsByClassName()
returns a list of all HTML elements with the provided class name. In your loop, you are only ever alerting the first element returned at index [0]
.
Try:
var x = document.getElementsByClassName("post");
for (var i = 0; i < x.length; i = i + 1) {
alert(x[i].getAttribute("id"));
}
<!DOCTYPE html>
<html lang="en">
<div id="blah1" class="post"></div>
<div id="blah2" class="post"></div>
<div id="blah3" class="post"></div>
<div id="blah4" class="post"></div>
<div id="blah5" class="post"></div>
</html>
</div>