Accessing HTML elements within JavaScript objects

Whenever I generate a new element dynamically using JQuery like this:

$("<div>",{id : "list"}).html("hello").appendTo("body");

and then create a JavaScript object with the selected element like so:

var obj = {el : document.querySelector("#list") }

Surprisingly, even after removing the element, when I print obj.el, it still shows:

<div id="list">hello</div>

I am able to change the content using obj.el.innerHTML = "foo"; But even after deleting the element with:

$("#list").remove();

The element is still present in the object obj. When printed, obj.el continues to show:

<div id="list">hello</div>

Why does this happen? Is there a more efficient way to store reference to an element without having to save a complex nested CSS selector which could impact performance?

Answer №1

Check out this helpful example that might assist you.

// consider this sample code: $("<div>",{id : "list"}).html("hello").appendTo("body");
var obj = {
  a : 5
};

// let's create another object for better understanding
var obj2 = {
  a : 3
};

document.write(obj.a + "<br>"); // 5
document.write(obj2.a + "<br>"); // 3

obj2.a = obj.a;

document.write(obj2.a + "<br>"); // 5

$("#list").remove();
delete obj.a;

document.write(obj2.a + "<br>"); // 5

obj2.a = obj.a;
document.write(obj2.a + "<br>"); // undefined

If you try the following in your scenario:

$("#list").remove();
var obj = {el : document.querySelector("#list") }

I believe that obj will be undefined!

Answer №2

If you want to enhance the el property, consider using getter and setter functions. Instead of directly storing the element in el, assign its value dynamically when it is accessed.

Try implementing it like this:

var obj = {
  get el(){
    return document.querySelector("#list");
  }
}

For a helpful demonstration, check out this demo.

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

Z-index creates an obstacle that prevents items from being clicked on

I am facing an issue with my container div that has an inset drop shadow applied to it. Inside this container, I have child elements and I want these children to be clickable. For the drop shadow to show, it is necessary to set the z-index of the child el ...

Guide to implementing if statements within a map function in JavaScript/Vue.js

Currently, I am developing a small application using Vuejs. In this application, I receive response data and then map it to a variable. However, there are some elements with empty arrays in the data. So, during mapping, I need to check a condition and ma ...

Using JavaScript AJAX to send a PHP POST request

I am encountering an issue where my data is not being inserted into the database. When I check the console log and network, I receive a blank response. The problem might stem from the fact that my JavaScript source code contains a mix of other stack overfl ...

Is it advantageous or detrimental to have a function within a React render return?

Many have questioned whether it's beneficial to have functions in Functional Components return an object. Take, for example: export const Button = ({...props}) => { const [isChecked, setIsChecked] = useState(false); return ( <d ...

Flex-wrap functionality in versions of Safari 6 and earlier

As I work on developing my website, I have been using flexbox to assist with the layout. It has been functioning well on most browsers, but I have encountered issues with Safari versions below 6.1. Specifically, I am struggling with flex-wrap as I want the ...

Finding the identifier for resources through excluding external influences

I am currently facing an issue with the full calendar plugin. In my set up, I have 3 resources along with some external events. The problem arises when I try to drop an external event onto the calendar - I want to retrieve the resource id from which the ev ...

Why isn't the custom script in my WordPress plugin executing properly?

I've been attempting to run a JS code in my dashboard.js file, but unfortunately, it's not working as expected. wp-content/ └── plugins/ └── desha-moulin/ ├── desha-moulin.php ├── dashboard/ │ ...

Message port in Chrome extension has been closed without receiving a response

I encountered an issue with my Chrome extension that I need help resolving. I am attempting to send messages from background.js to my content script. The first message goes through smoothly, but the second one results in the following error: _generated_bac ...

Implementing Vue.js click event behavior on a component within the template

Encountering an issue while developing Vue's template onclick event. Trying to open a module when clicking a file, I have looked at some samples with native code, but it does not quite fit into my code and I cannot reach the console. Here is my code: ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

Unnecessary Extra Spacing in Every <li> Tag

After searching thoroughly, the problem still remains elusive. Space seems to be mysteriously added to each list item within this code block. My suspicion lies with the for loop as it consistently adds a fixed amount of space. https://i.sstatic.net/0giRG. ...

Cufon Superfish conceals dropdown menu text on Internet Explorer 8

When using Cofunized text in my drop downs with superfish, I encountered an issue where the dropdown text is hidden in IE8. I attempted to apply a fix from a suggested link (https://forum.jquery.com/topic/jquery-fix-superfish-cufon-in-ie8) but unfortunat ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

Issues with Jquery $.ajax functionality not being successful

I am currently utilizing Codeigniter and attempting to fetch a result through an Ajax call with jQuery. The Select Box I have is populated from the database in the following manner: echo "<select id=\"agent_select\" name =\"agent_select& ...

What makes CSS so intricate and challenging to navigate?

While going through a CSS tutorial, I encountered this detailed definition: .content div { -moz-box-shadow:inset 0px 1px 0px 0px #ffffff; -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff; box-shadow:inset 0px 1px 0px 0px #ffffff; backgroun ...

What is the most effective method for creating and removing a component just once in a React application? (Is it acceptable to use unused setters from useState?)

On my canvas, I have a large game object that should only be created once when the component is rendered and should persist until the component is removed. (I want to avoid making changes to the game structure by adding storage in a Context or Redux. I pr ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

How can I programmatically close an md-select when a button is clicked within the md-select?

How do I close the md-select menu when a button inside it is clicked? JavaScript $scope.closeSelectBox = () => { var esc = jQuery.Event("keydown"); esc.which = 27 esc.keyCode = 27 $(document).trigger(esc) } HTML <md-input-container style ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Unable to perform a setter operation within a loop structure

I've been working on crafting a hero quest-style script lately. The script involves navigating through an array of events where the player either moves or encounters enemies, triggering a battle. After meticulously writing the script and reviewing i ...