In my HTML I have a content div that contains articles created by a php script and handled with JQuery and Javascript. With Javascript I collect those articles into an array with the ‘getElementsByClassName’ function.
The scripts and HTML I’m writing here are simplified. I need this array because I’m trying to make that if the length of the array is larger than 10, only 10 articles are displayed per page. So page 1 will be index 0 to 9 of the array, page 2 index 10 to 19, etc.
Now,
Take this html code.
<body>
<div id="content">
<div class="article">
<p>Article 1</p>
</div>
<div class="article">
<p>Article 2</p>
</div>
<div class="article">
<p>Article 3</p>
</div>
</content>
</body>
And this Javascript code.
$.post("getarticles.php",{ page:"home" } ,function(data){
//place the content
document.getElementById("content").innerHTML = jQuery.trim(data);
//put elements in array
arrArticles = document.getElementsByClassName("article");
alert(arrArticles.length);
document.getElementById("content").innerHTML = "";
alert(arrArticles.length);
})
The first alert gives me “3”, which is correct.. But the second alert gives me “0”. Why is the array losing it’s elements after the elements have been put in it?
By the way, the ‘data’ variable is a string of HTML passed on by a php script.
For example: In the php script I have the code
echo "<div class="article"><p>Article 1</p></div><div class="article"><p>Article 2</p></div><div class="article"><p>Article 3</p></div>"
&
document.getElementById("contentWrap").innerHTML = "";
I know this is causing the problem, but I don’t know why. Can anyone explain or provide an alternative?
Thanks in advance
It looks like document.getElementByClassName is returning a reference to the element array which is being updated when you change the mark up. Not sure why; perhaps somebody better informed than me can answer that.
Using jQuery to select the array worked for me: