JS appears a BUG analysis

Today, according to JS DOM programming to do a simple project. In simple terms, by clicking a label, trigger a JS function, find an element node in the whole DOM tree through THE ID value through DOM method (the document only has the IMG label), and then replace the img label resource image through DOM method, so as to achieve the click-image replacement effect.

The BUG description

When all the parts are written, click the showPic() function that should trigger the replacement of the img tag SRC attribute as follows:

function showPic(whichpic) {
    var source = whichpic.getAttribute("href");
    var placehold = document.getElementById("placehold");
    placehold.setAttribute("src",source);
}
Copy the code

Then the A tag and img tag look like this:

<a href="images/fireworks.jpg" onclick="showPic(this); return false;"title="A fireworks display">Fireworks</a>      
Copy the code
<img id="placeholder" src="images/placeholder.jpg" alt="my image gallery" />
Copy the code

Of course, the obvious id for showPic() is “placehold”, but the IMG id is “placeholder”, so showPic() ends at that point

var placehold = document.getElementById("placeholder");
Copy the code

But the browser didn’t pop any bugs and proceeded smoothly. This is a good thing for web browsers, because there are all sorts of bugs/browser compatibility issues that can go wrong when browsing the web, and the process can’t get stuck. “output error” and “output error” are always better than the experience of reporting errors directly. For developers, debugging becomes more difficult. (here set a flag, later learn js debugging method)

Can’t retrieve id, what does JS do

GetElementbyid () returns a non-string NULL if it can’t find a node element in the document with the ID. Let’s test it with JS code. Retrieves a DOM node element from the document by ID, saves it to a variable, and prints it as follows:

function showPic(whichpic) {
    var source = whichpic.getAttribute("href");
    var placehold = document.getElementById("placeholder");
    alert(placehold.id);
    placehold.setAttribute("src",source);
}
Copy the code

When the element node can be retrieved by ID, the browser outputs [Object HTMLImageElement] to view its properties. Browser prints [NULL] when element node cannot be retrieved by ID

At the end

Be oneself from the beginning to understand a small problem in place, feel writing blog this kind of method is quite impressive.