Should we employ getAttribute() or avoid it entirely? That is the ultimate query

Similar Topic:
JavaScript setAttribute vs .attribute=
javascript dom, how to handle "special properties" as versus attributes?

On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes in my code. Instead of using var link = a.href, I've been advised to use

var link = a.getAttribute('href');
and setAttribute() for assignment. I usually brush it off, but now I'm curious about when it would be more appropriate to use one method over the other.

People claim that using

var link = a.getAttribute('href');
is the right approach, but no one explains why. So, I'm left wondering in which scenarios this method is preferable.

When should I opt for

var link = a.getAttribute('href');
instead of var link = a.href?
And when is it better to use setAttribute() instead of directly assigning a value to a member, like `a.href = 'someURL';

Answer №1

It is essential for individuals to provide justification when recommending a particular practice.

One reason to avoid using getAttribute and setAttribute is due to known bugs in the implementation of those DOM methods in older versions of Internet Explorer, up to and including version 8. Additionally, different browsers may exhibit variations in how they handle DOM properties when get/setAttribute is used.

Despite these differences, browsers tend to be consistent when it comes to DOM properties, making it easier to write code that works across different browsers by utilizing DOM properties. It is worth noting that some browsers may not create DOM properties for non-standard HTML attributes, but they can still be set using properties.

Another benefit of utilizing DOM properties is the increased speed of property access compared to using get/setAttribute.

Although HTML5 aims to standardize some of these behaviors, it is important to recognize that HTML5 is a "living specification" rather than a W3C standard. This means that while it documents browser behaviors and desired outcomes, it does not clearly distinguish between the two, making it more of a wish list than a defined standard.

Edit July 2017

Both the W3C and WHATWG have been actively publishing updates to the HTML5 specifications, with the WHATWG providing almost daily updates to the HTML and DOM standards. It remains to be seen if one organization will eventually take precedence over the other.

Answer №2

When dealing with standard attributes that are universally supported by browsers, I prefer to use direct property access like obj.href because I find it more readable and reliable.

For non-standard attributes or ones I have created myself to store data on an object, I opt for get/setAttribute().

I have never encountered any issues using direct property access like obj.id, obj.href, obj.className, obj.value, etc... in any browser, so I see no reason to always resort to get/setAttribute().

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

Sometimes, a record goes missing from a PHP/JSON array

When calling a PHP script to retrieve results and converting the array into a JavaScript array for a multiple choice quiz, I encountered an issue where certain records were missing unexpectedly. It seems to occur randomly as there is no specific pattern to ...

Utilize JSON parsing with a reviver parameter to filter out specific object properties

In the process of developing a Node.js server, I am working on a particular service that requires accepting a stringified JSON object while also implementing field whitelisting. To achieve both of these objectives, I intend to utilize JSON.parse() with the ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

How to Insert JSON into React Component's Attribute?

I am struggling with setting the value of a React component using JSON in the attribute. I want to concatenate a letter or word, but it doesn't seem to work. Is there a correct way to combine strings within a Component's attribute? In this case, ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

Tips on displaying JSON data in the browser console using console.log for API consumption

I'm having trouble creating an api to output data parsed from an xml file. When I console.log the necessary data, it shows up fine, but when I try to display it in the browser, I only get an empty array. Any suggestions on what could be causing this i ...

What exactly does the term "library" refer to in the context of jQuery, a JavaScript

I'm confused about the concept of a library - when it comes to jQuery, can it be described as a large file containing multiple plugins that are pre-made and ready for use? ...

Attach a click event handler to a D3 element

Upon loading the page, the nodeClick() method is called without any clicking action. How can I adjust it so that the nodeClick() function is only triggered when I click on the element? Here is the code snippet: var node = svg.selectAll(".node") .on( ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

Using nightwatch.js to verify elements across different parts of a webpage

Currently engaged in working with nightwatch.js and encountering an issue with a particular page file structure: sections: { table: { selector: '.sr-filterable-data-layout--collection', elements: { header: { ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

Using Typescript to pass a property as one of the keys in an object's list of values

In my React Native project, I need to pass a string value from one component to another. The different options for the value can be found in the ScannerAction object: export const ScannerAction = { move: 'move', inventory: 'inventory&apo ...

What sets apart using 'self.fn.apply(self, message)' from 'self.fn(message)', and what are the advantages of using the former method?

Whenever I come across code that looks like thisnewPromise.promiseDispatch.apply(newPromise, message), I can't help but wonder why they didn't simply use newPromise.promiseDispathch(message) ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Creating functions within the $scope that do not directly access the $scope object

tag, I am looking to create a $scope function that specifically manipulates the variables it receives. To test this functionality, I have set up a Plunker available at http://plnkr.co/edit/BCo9aH?p=preview. In my setup, there is an ng-repeat loop that lis ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

Navigating to lower levels of JSON data in JavaScript instead of starting with the top level

Using a microservice, I fetch multiple sets of JSON data and display them on a Vue.js-powered page. The structure of the data is as follows: {"data":{"getcompanies": [ {"id":6,"name":"Arena","addr ...