Does JavaScript return null or empty values for all DOM manipulating functions?

Currently diving into the realm of JavaScript with the help of "Professional Javascript for Web Developers," but running into a roadblock when attempting to manipulate the DOM tree.

Testing out an example locally, which works perfectly fine on jsfiddle:

http://jsfiddle.net/y5nfL/

However, upon testing it locally, I'm encountering the following error in the console:

Uncaught TypeError: Cannot read property 'tagName' of null

My index.html file looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>JS sandbox</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="myDiv"></div>
    </body>
</html>

Here's what my script.js file contains:

var div = document.getElementById("myDiv");
alert(div.tagName);

I've tried numerous other methods such as cloning elements, but still end up with getElementById() returning null every time. What could be causing this issue? Any insights would be greatly appreciated.

Answer №1

After running your script, the DOM is empty beyond the script tag. It's important to ensure that the DOM is completely loaded before attempting to interact with it.

An alternative approach would be to relocate your script tag to the bottom of the document, just before </body>.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the DIV using instructions sent from the server

Looking to create a webpage that retrieves data from a mySQL database, specifically a value of 0 or 1. The goal is to have a div on the page automatically refresh with the latest value from the database at set intervals. Additionally, it's important ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...

Tips for automatically choosing several choices from a multiple-select using Chosen.JS

I am struggling to programmatically select multiple values in a multiple select using chosenJS/chosen.js while still ensuring that the selected values are bound to my ng-model (angularJS). In this scenario, I have a list of users, some of whom are already ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

Transferring an Array into an Object within an Object Using Angular

I'm currently diving into Angular and I decided to tackle angular.copy with a simple example. My goal is to create an Object using a Service, and then create a new Object that only contains certain elements from the original Object. Check out the ful ...

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

Challenges with loading elements in Protractor

I'm feeling a bit confused about Protractor at the moment. It seems like sometimes my elements load in time for the next action to happen, while other times they do not. I'm assuming this has something to do with its asynchronous nature. For ex ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

Using Vue.js to make an AJAX request to an API that returns a list in JSON format

I am attempting to utilize an AJAX call with the free API located at that returns a list in JSON format. My goal is to display the result on my HTML using Vue.js, but unfortunately, it doesn't seem to work as expected. This is my JavaScript code: va ...

Completing forms and tracking browser history when the document is ready

In my current webpage, I have code that automatically submits the form when the DOM is ready: $(function () { $('form').submit(); }); However, I've noticed that when a user clicks the back button on their browser on the next page, it t ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

``Incorporating Vue.js: A Guide to Emphasizing the Chosen Selection from Numerous Lists

I am currently utilizing Vue.js and have multiple lists displayed, but I only wish to select and highlight one element at a time. Currently, every click results in multiple items being highlighted. I hope that explanation is clear. Below are the snippets o ...

Exploring the application of styles within the shadow DOM

I'm experimenting with applying styles to the shadow DOM. Consider the following example: const element = document.getElementById("bar"); const shadowRoot = element.attachShadow({ mode: "open" }); const greeting = document.createElement("p"); gree ...

Convert string IDs from a JSON object to numerical IDs in JavaScript

My goal is to convert the IDs in a JSON object received from PHP into numeric keys using JavaScript. The initial structure of my JSON object looks like this: let foo = {"66":"test","65":"footest"}; What I aim for is to transform it into this format: let f ...

redux - managing asynchronous storage using key-value pairs

Utilizing associative arrays with redux and storing them in async storage for later retrieval is my current challenge. When using redux, I am able to quickly access the values and efficiently map the content into cards in my react native app. However, aft ...

ReactJS with conditional closing tags

Here is a sample json response : {id: 1, name: a} {id: 2, name: b} {id: 3, name: c} {id: 4, name: d} {id: 5, name: e} {id: 6, name: f} I am looking to organize these by pairs in my React component like so : <div className="group-item"> ...

What are the steps to manipulate a scene using three.js?

This HTML page showcases a scene with various points that can be comfortably zoomed in using the mouse wheel. However, I am looking to implement the functionality to drag the scene after zooming in. The idea is to click and hold the left mouse button whil ...

Cross-origin resource sharing policy is preventing a request from the client-side to the server

I am currently working on a Vue.js application and I am facing an issue with CORS policy blocking my backend requests. I am using axios to make the request to the backend for data that I need to display charts on the UI. Here is the code snippet of my char ...

When trying to access a specific key in a JavaScript object, it may

I am currently working on optimizing the performance of my express application for production. I came across a helpful video tutorial at https://www.youtube.com/watch?v=WiZ2Py97rio, where the presenter explains a config object with keys for 'developme ...