What is the best approach for monitoring read-only attributes of an HTMLElement using JavaScript?

When attempting to observe the "isConnected" property of an HTMLElement, I found that it is a read-only property and there is no propertyDescriptor for it. This means that the traditional method of overriding getters and setters or creating a proxy object is not applicable.

I have learned about mutationObserver, but it seems they can only observe attributes. Additionally, they are resource-intensive for our application since we need to observe the "isConnected" property on every dynamically created element (80% of our application consists of dynamic elements).

Are there any alternative methods for observing changes to read-only properties?

Answer №1

If the original poster wants to monitor DOM changes dynamically, they may want to consider using the MutationObserver API. While the OP may not be able to directly observe a node's isConnected attribute, they can still obtain similar information about whether a node is part of the rendered DOM by listening for a 'childList' mutation type.

function handleDomChanges(mutationsList, observer) {
  for (const mutation of mutationsList) {
  debugger;
    const {
      type, attributeName,
      addedNodes, removedNodes
    } = mutation;
    if (type === 'childList') {
      if (addedNodes.length >= 1) {

        console.log(`${ addedNodes.length } child node(s) has/have been added`);
      }
      if (removedNodes.length >= 1) {

        console.log(`${ removedNodes.length } child node(s) has/have been removed`);
      }
    } else if (type === 'attributes') {
      console.log(`The ${ attributeName } attribute has been mutated.`);
    }
  }
};

const config = {
  attributes: true,
  childList: true,
  subtree: true
};
const targetNode = document.querySelector('#app');

const observer = new MutationObserver(handleDomChanges);

observer.observe(targetNode, config);
// observer.disconnect();


const listNode = document.querySelector('#navList');

const itemNode = document.createElement('li');
const testNode = document.createElement('a');
testNode.href = '\/';
testNode.textContent = 'test 4';

itemNode.appendChild(testNode);

console.log({
  testNodeIsConnected: testNode.isConnected
});
listNode.appendChild(itemNode);

console.log({
  testNodeIsConnected: testNode.isConnected
});
testNode.remove(); 

console.log({
  testNodeIsConnected: testNode.isConnected
});
itemNode.appendChild(testNode);

console.log({
  testNodeIsConnected: testNode.isConnected
});
.as-console-wrapper {
  bottom: 0;
  left: auto!important;
  min-height: 100%;
  width: 50%;
}
<div id='app'>
  <nav>
    <ul id="navList">
      <li><a href="/">test 1</a></li>
      <li><a href="/">test 2</a></li>
      <li><a href="/">test 3</a></li>
    </ul>
  </nav>
</div>

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

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next »", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

What is the most effective way to integrate a Link/URL button into the remirror toolbar?

I have chosen to utilize remirror for constructing a WSYWIG editor. The specific requirement is to include a "Link" icon in the toolbar, allowing users to select text and easily add a hyperlink by clicking on it. Although I came across the LinkExtension ...

Waiting in Python using Selenium until a class becomes visible

Currently, I am trying to extract information from a website that has multiple web pages. This is how my code appears: item_List = [] def scrape(pageNumber): driver.get(url + pageExtension + str(pageNumber)) items = driver.find_elements_by_class_ ...

What is the optimal method for creating and testing AJAX applications on a local server, then effortlessly deploying them online?

Exploring AJAX development is new to me. The challenge I've encountered so far is dealing with the same-origin policy, which requires modifying host information strings like absolute URLs in JavaScript files every time I deploy local files to remote s ...

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

Display the json encoded result of a MySQL SUM() query

I am attempting to use JSON to print the total sum of a price. Here is my current approach: $query="SELECT SUM(cost) FROM `Service`"; $result = mysql_query($query); $json = array(); while($row = mysql_fetch_array($result)) { $json[&a ...

I am unable to populate MongoDB references using Node.js

I need to display the user's location details on the screen. For example: name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy" When the getuser function is called, I want to show the City and Town name. This is the implementation: U ...

The function ng-click does not successfully uncheck ion-radio

In the process of developing my application using the ionic framework, I encountered a challenge where I needed to deselect an ion-radio button when clicking on an input tag. Despite attempting to achieve this functionality through this ionic play link, I ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

What is the best way to load a local JSON file as the initial data source in Express and use it as an in

I'm in the process of creating a basic todo application using node.js express, and I've decided to work with an in-memory resource instead of utilizing a database. There's a local json file todo.json that contains some initial data which I ...

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Deducting time from the present moment

I am facing a scenario where I have 2 strings representing the minute and hour for a specific function to execute at. I aim to validate if the specified minute and hour, present in string format and retrieved from my database, are within a 5-minute window ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

Is there a method for redirecting my page to a specific href link without triggering a page reload?

This is my HTML code. <a href="http://127.1.1.0:8001/gembead/emstones.html?car=36">Car</a> I am trying to redirect to a specific page with parameters without fully reloading the current page. Is there a way to achieve this task? I believe the ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...

What is the proper way to search for a specific string within a JavaScript array during an iteration?

I am working with an array that is continuously updated with new string elements every 2 seconds. The code snippet below showcases how the updates are processed: //tick world setInterval(function(){ doTradeUpdate(); },5000); function doTradeUpdate(){ ...