简体   繁体   中英

Javascript Not Detecting HTML Elements

Okay, believe me that I have many "p" tags on my HTML document. Here is my Javascript code:

var elements = document.getElementsByTagName('p');
var i;
window.onload = clicker();
function clicker() {
    alert(elements.length);
    for(i=0;i<elements.length;i++) {
        alert('looping');
        elements[i].onClick = function() {
            this.style.color = '#33CC33';
        }
    }
    setInterval(clicker, 0);
}

Notice my first alert statement in there. It alerts "0" to me, which makes no sense. My problem is that none of the "p" tags are being stored in the elements variable at all, therefore making my for loop not run. The HTML is filled with a lot of PHP but here is the top snipped to prove to you that I do have a "p" tag:

<!DOCTYPE html>
    <head>
        <title>Gwiddle - FTP</title>
        <link rel='stylesheet' type='text/css' href='stylesheet.css' />
        <script type='text/javascript' src='script.js'></script>
    </head>
    <body>
        <div id='banner'><p>Gwiddle FTP</p></div>

You are trying to access your DOM before it has loaded.

Try putting this: var elements = document.getElementsByTagName('p'); inside your clicker() function:

var elements;
var i;
window.onload = clicker();
function clicker() {
    elements = document.getElementsByTagName('p');
    alert(elements.length);
    for(i=0;i<elements.length;i++) {
        alert('looping');
        elements[i].onClick = function() {
            this.style.color = '#33CC33';
        }
    }
    setInterval(clicker, 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM