0

.attribute in Javascript

let friendDiv = document.getElementById("friend");
friendDiv.className = "list";

VS

setAttribute in Javascript

let friendDiv = document.getElementById("friend");
friendDiv.setAttribute("class","list");

VS

.attr in Jquery

$("#friend").attr("class", "list");  
Prathna
  • 1
  • 2
  • Depends on whichever language you are comfortable with. – Krishna Prashatt Apr 16 '19 at 09:36
  • I would say `friendDiv.classList`, you could then use `.value`, `.add`, `.remove`, `.toggle`.. etc. – Keith Apr 16 '19 at 09:36
  • Possible duplicate of [When to use setAttribute vs .attribute= in JavaScript?](https://stackoverflow.com/questions/3919291/when-to-use-setattribute-vs-attribute-in-javascript) – f-CJ Apr 16 '19 at 09:40

2 Answers2

0

This depends on what you are trying to achieve, or which attribute you want to change

Normally the setAttribute versions are longer, so the shorter ones should be preferred. Sometimes, there is a DOM property that is even more convenient than the setAttribute since it provides for methods, like classList But you may want to add an attribute, that is not part of the DOM like <span my-span-is-awesome></span>. Here you have no other choice than using setAttribute.

I prefer not to use jQuery where I can avoid it.

yunzen
  • 32,854
  • 11
  • 73
  • 106
0

As stated in this similar question/answers: When to use setAttribute vs .attribute= in JavaScript?

setAttribute and getAttribute are just needed for non-standard HTML attributes.

You should be using .attribute for standard attributes.

If you are using JQuery, you can always use attr because can be used for standard and non-standard attributes.

let test = document.getElementById('test');

console.log('Accessing custom attribute with .attribute:', test.custom);
console.log('Accessing standard attribute with .attribute:', test.className);
console.log('Accessing custom attribute with getAttribute:', test.getAttribute('custom'));
console.log('Accessing standard attribute with getAttribute:', test.getAttribute('class'));
console.log('Accessing non-standard attribute with jquery attr:', $(test).attr('custom'));
console.log('Accessing standard attribute with jquery attr:', $(test).attr('class'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test" class="myClass" custom="anything">My test</div>
f-CJ
  • 4,235
  • 2
  • 30
  • 28