I am trying to create a simple recipe-app with javascript. I have 3 HTML files: index.html, create.html, edit.html and 2 JS files.
I have a couple of DOM elements. One on index.html, Two on edit, Two on create. Now when I open index.html I get an error:
recipe.js:14 Uncaught TypeError: Cannot set property 'value' of null
The problem here is that the code that the error is it's about edit.html not index.html. Same problem on edit.html
Uncaught TypeError: Cannot read property 'appendChild' of null
at recipe.js:55
recipe.js code 55 is about index.html, not edit.html.
Is there a way to target an HTML file when using DOM.
document.getElementById("edit-body").value = getRecipeBody();
I want the code above to be only for edit.html, not for index.html or create.html.
document.getElementById('recipes').appendChild(recipeEl)
I want this code to be for index.html not for other HTML files because there is no #recipes ID on those files. The #recipes is only on index.html
I am using localStorage.
window.location.pathname would let you execute code for a specific path.
if(window.location.pathname === '/edit.html') {
document.getElementById("edit-body").value = getRecipeBody();
}
Note that if you load index.html
by default (as in, http://localhost:80/ as opposed to http://localhost:80/index.html ), then the pathname will simply be /
, so make sure you handle both of those, ie:
if(window.location.pathname === '/index.html' || window.location.pathname === '/') {
document.getElementById('recipes').appendChild(recipeEl)
}
A better approach would be to code it defensively. Check that the element you're getting exists before running a function against it. For example:
var editEl = document.getElementById("edit-body");
if (editEl) {
editEl.value = getRecipeBody();
}
Instead of either of these, you could also just load index.js
on index.html
, edit.js
on edit.html
, etc., though you'd want to split out any shared functions into a separate (common) JS file.
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.