Unexpected behavior in IE8 with setAttribute following Object extension

In my current project, I've implemented a custom micro-library similar to JQuery, but tailored specifically to my needs.

window.$ = function(selector, context, undefined) 
{
    var getSelectorTest = function(selector, context, undefined)
    {
        var el;
        var selector_key = selector.slice(0, 1),
            matches = {
                '#': 'getElementById',
                '.': 'getElementsByClassName',
                '@': 'getElementsByName',
                '=': 'getElementsByTagName',
                '*': 'querySelectorAll'
            }[selector_key],
            selector_value = selector.slice(1);

        //add fallback for getElementsByClassName is not supported e.g. IE8
        if(matches === 'getElementsByClassName' && !document.getElementsByClassName)
        {
            matches = 'querySelectorAll';
            selector_value = selector;
        }

        // now pass the selector without the key/first character
        el = (((context === undefined) ? document: context)[matches](selector_value));
        return el;
    };

    var elem = getSelectorTest(selector, context, undefined);

    //Extend elem before returning it
    elem.attr = function(name, value) {
    if(value)
    {
        this.setAttribute(name, value);
        return this;
    }
    else
    {
        return this.getAttribute(name);
    }   

    return elem;
};

Upon executing the below code:

<script>
    domReady(function(){ //https://github.com/cms/domready
        var el_1 = $('#container-1');
        el_1.attr("data-test", "random_value");
    });
</script>

My output differs when using IE8:

<div id="container-1" attr="function(name, value) {
            if(value)
                {
                    this.setAttribute(name, value);
                    return this;
                }
                else
                {
                    return this.getAttribute(name);
                }

        }" data-test="random_value">

This issue doesn't occur in Chrome and Firefox where the expected output is

<div id="container-1" data-test="random_value">
. How can I resolve this discrepancy?

Note: I'm currently utilizing the 'HTML' tab within IE8 Developer Tools (F12) to investigate this behavior.

Answer №1

To avoid issues with IE8 interpreting the attr() function as setting an attribute on the element itself, consider attaching it to the prototype of the Element object for better results.

Element.prototype.attr = function(name,value){ ...

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

How can jQuery Validate show validation messages specific to each field?

I need to validate numerous mandatory fields and display alert messages in a specific format: "Please fill in" followed by the field label. Currently, I am manually implementing this validation method as shown below: $("#myform").validate({ rules: { ...

How can a command in a test be executed that is located within a specific "section" in Nightwatch?

I've been utilizing nightwatch for my test automation. Within my page object, I have a "section" containing various commands. However, when attempting to call these commands in the test script, I encountered an error stating "section is not a function ...

A guide to downloading a file linked to Javascript with the help of Java

I have a unique request here. I am looking for a solution using HttpUrlConnection that can interact with JavaScript directly on a webpage, instead of relying on Selenium as a workaround. Can anyone assist me with this? The webpage contains a link (hidden ...

Calculating grand total upon form initialization

Hey there! I'm working on an input that fetches values and triggers the fntotal function to show a total. The issue I'm facing is that when the form loads, the total doesn't display initially - it only works when values are changed. <inp ...

Summing Up Values in Jquery Loop Through Table Rows

I am facing a challenge with a table that contains a textfield for inputting numeric values. This textfield is part of a repeated row table, with the ID 'amount'. My goal is to calculate the sum of all values entered in the textfields with the ID ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...

Basic inquiry about Ajax

Would you like to know a simple solution for refreshing a specific area of your website using ajax? Instead of having JavaScript constantly checking for changes on the server, is there a way for the server to send data when a certain event occurs? Imagine ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

Tips on entering a text field that automatically fills in using Python Selenium

One of the challenges I am facing on my website is an address input text field that gets automatically populated using javascript. Unlike a drop-down field where you can select values or a standard text field where you can manually type in information, thi ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

Using the Flow type checker with React library results in complications

I'm fairly new to JavaScript and React, so I appreciate your patience! I've recently started a project using create-react-app with React version 16.12.0. I installed a library that seems to be utilizing Flow. When attempting to use this library ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

The Vue user object appears to be null in spite of being defined and clearly visible in the log output

There seems to be an issue with my function that utilizes a person's user name to retrieve the current User from the database. Initially, when I log the current user within the function, everything works perfectly. However, once I attempt to access it ...

Disable all components on the web page using the Wicket DisableComponentListener

When using an ajax button in my Wicket application, the following code works perfectly: @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.getAjaxCallListeners().add ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

Interactive table with dynamic data retrieval

I need help displaying data dynamically from a datatable using an API. The API I am working with is located at this URL and I am utilizing the bootstrap4 datatable. You can also find my code on this JSFiddle. Can someone provide guidance or an example on h ...