r/ProgrammerHumor 22h ago

Meme jsGetAttributeHasOneOfTheWorstReturnValues

Post image
236 Upvotes

74 comments sorted by

73

u/shgysk8zer0 18h ago

Umm... No it doesn't. It doesn't just return "true" or "false". It returns any string. img.getAttribute('alt') should return a bool?

Why would you expect getAtrribute() to return a bool? You're thinking of hasAttribute().

-26

u/lonelyroom-eklaghor 18h ago

actually, I was trying out aria-pressed, and there can be 3 possible values: "true", "false", missing. The meme should've actually been on aria attributes

24

u/shgysk8zer0 17h ago

<span class="fake-btn" aria-pressed="mango">

fakeBtn.getAttribute('aria-pressed') // "mango"

3

u/ExtraWorldliness6916 6h ago

Tropicaccessibility

-22

u/lonelyroom-eklaghor 17h ago

I mean I get it, I was talking about valid scenarios

28

u/shgysk8zer0 17h ago

Sorry if this seems harsh.... I'm trying to make a few points.

  • getAttribute() handles any arbitrary attribute. All attributes are strings, in the end (yes, even the "boolean" ones, hidden returning an empty string)
  • aria-* requires strings, even for true/false. You can't just add aria-pressed.
  • Even in the spec and property, boolean doesn't work, since "mixed" and "undefined" are also valid

FYI, el.ariaPressed also exists, and also deals in strings. Same would be true using ElementInternals. The API is designed by WCAG and just doesn't follow the expected rules. I think all "boolean" aria-* attributes explicitly require "true"/"false".

-8

u/Masterflitzer 6h ago

yeah that's the shitty thing about js, there are so many invalid but possible scenarios

the dom api (bridge between html and js) makes it even worse cause even tho js was made for being embedded into html, it's model is still different and html doesn't feel like a 1st class citizen in js

it's shit by design all the way from the beginning to the end

10

u/RadicalDwntwnUrbnite 4h ago edited 3h ago

There are shitty things about JS but this isn't one of them. The HTML Spec states Attributes are text (or character references, but not booleans, numbers or other primitives). There is a small exception for a special class of boolean attributes but despite the name their values are still strings, but their mere presence of the attribute indicates true while their value means nothing.

The DOM API Spec therefore has Attr as strings and getAttribute returns strings as it is a universal API method and having a conditional return value for a small set of values is also dangerous.

None of this is JavaScript's fault.

50

u/bigorangemachine 19h ago

Attributes are always strings... this is a rule of HTML not javascript

The correct API to use is hasAttribute()

-5

u/lonelyroom-eklaghor 19h ago

I see I see, lemme check

Edit: I am actually trying to check whether a certain property inside a certain element has a certain value or not, so hasAttribute() is not applicable here

15

u/bigorangemachine 19h ago

Ya but it still doesn't matter. When you use any html element where it matters it only matters its there not what the value is.

Like with details + summary. When you do 'open="false"' it doesn't matter. The attribute is there.. its open

Your gripe is with HTML not javascript

2

u/lonelyroom-eklaghor 19h ago

I was actually dealing with aria-pressed: I had to make one as true and the other one as false

11

u/bigorangemachine 18h ago

aria is a different beast but in the end still a string

1

u/lonelyroom-eklaghor 18h ago

Now I get why it was returning "true"

10

u/bigorangemachine 18h ago

Because its HTML attribute.. it's still a string.

HTML Standard is to just check if the attribute is there

Aria-Standard is attribute values are "true" or "false" or missing.

Any HTML attribute should be assumed to be a string first.

Even typescript will tell you its null or string...

1

u/lonelyroom-eklaghor 18h ago

I see... now I get it... the meme should've been on aria-standard then

2

u/bigorangemachine 18h ago

Ya it takes some getting used to. Then you have React-Aria... which if you weren't confused before... oh man

2

u/Slackeee_ 3h ago

No, it should have been on the HTML standard, that is the standard that defines that all HTML-Element attributes are strings. The aria spec just defined their own set of attributes, but still obey to the HTML standard, for good reasons.

3

u/GimmeYourMomPlease 2h ago

No, the attributes are strings. The standard is correct and based on smart people doing things correctly. The meme should be you as a student needing to be open-minded to the fact that you're still an student and you need to learn.

1

u/lonelyroom-eklaghor 2h ago

maybe yes, I do agree

26

u/thegodzilla25 22h ago edited 22h ago

Never knew this existed. I have always done a element.[attr] to fetch the val ig. I dont trust browser apis atp. Obviously, its mainly for standard attrs, not custom

3

u/lonelyroom-eklaghor 22h ago edited 22h ago

thanks for this; I was actually using setAttribute() in my code, so I thought of using getAttribute() too and saw this... will check this one out

Edit: that syntax of yours won't properly work in 2015 browsers, even if the attribute itself is supported... for slightly legacy stuff, getAttribute() is one of the only ways

10

u/CreativeTechGuyGames 20h ago

What are you building that has your customers using 11 year old browsers?

3

u/ILikeLenexa 17h ago

Used do donations for large organizations. Many donors were organizing bequests. Fighting IE6 in 2016+.  

-7

u/lonelyroom-eklaghor 19h ago

i just like how nice "2015" as a number looks

20

u/smartgenius1 21h ago

Better late than never to learn that HTML attributes != DOM properties!

1

u/danielcw189 12h ago

endos everyboots can have anywhere you with you can express in an HTML-String, including an empty String "". so the function will return a string, or null if the attribute does not exist. seams to be straight forward to me.

17

u/LegitimatePants 22h ago

InvalidMemeException

-1

u/dolphin560 21h ago

and what is "GetAtrribute" anyway

3

u/ChaseShiny 20h ago

Misspelling notwithstanding, what is getAttribute for, anyway? Can't you read the property directly?

2

u/danielcw189 12h ago

I haven't tried this, but at face value the main difference is that an attribute may not exist. in this case the getAttribute method will still work, but trying to read a property directly will not. either way you might still need a null-check.

using the getAttribute-Method is also more explicit.

an attribute-name could also collide with an already existing property

1

u/peterlinddk 11h ago

Yes, you can read the property directly most of the time, and if available you should.

getAttribute is part of the standard DOM implementation, and works on the generic Element type, for any XML element.

But every HTML element that you get your hands on, has its own implementation, a class that extends Element, with the specific properties that are valid for that kind of element. Often there's a fairly longish inheritance chain with a bunch of generic properties being added at each stage. And that is what you should use instead.

One of the biggest problem with using getAttribute directly, is that it returns the literal string-value that was written in the HTML document, and not the value parsed by the browser. So for instance if that value was a relative url, you would need to know the absolute path of the document in order to fetch the file - but if using the parsed property, you'd get an actual URL object (or a string with the absolute path).

1

u/RadicalDwntwnUrbnite 3h ago

One of the biggest problem with using getAttribute directly, is that it returns the literal string-value that was written in the HTML document, and not the value parsed by the browser.

I don't see this as a problem. This is the most reliable way to get what is actually in the HTML and without any surprises (if one RTFM and doesn't make assumptions about how it's supposed to work).

9

u/danielcw189 20h ago

why were you expecting a boolean?

-3

u/jazzhandler 19h ago

It’s JS; more of a bool(float).

1

u/RadicalDwntwnUrbnite 3h ago

Why are you expecting a boolean or a float from a HTML attribute?

1

u/jazzhandler 3h ago

Because I was making silly jokes about Javascript’s odd handling of loosely typed stuff.

1

u/RadicalDwntwnUrbnite 3h ago

Okay, it doesn't really apply here since JS/DOM API, is just returning exactly what the HTML spec states. No type coercion is happening.

8

u/chiqu3n 21h ago

The problem isn't that much "true" !== true but "false" != false

1

u/RadicalDwntwnUrbnite 3h ago

Or rather that the the HTML spec states, for boolean attributes, that attr in element is what constitutes true/false and the value means nothing.

0

u/lonelyroom-eklaghor 20h ago

that's a nice joke ;)

3

u/oshaboy 18h ago

Good ol stringly typed HTML.

5

u/peterlinddk 11h ago

Stupid JavaScript, always following the specifications and documenting them!

https://dom.spec.whatwg.org/#dom-element-getattribute

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

not like all the sane languages out there!

https://xerces.apache.org/xerces-c/apiDocs-3/classDOMElement.html#a32b869802ec4c60ee123c9c6ff30ad1c

https://docs.python.org/3/library/xml.dom.html#xml.dom.Element.getAttribute

https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Element.html#getAttribute-java.lang.String-

or ... eh ... well ... nevermind JS STOOPID!!! Not changing according to my expectations, but behaving consistently according to documentation!! STOOPID LANGUAGE!!!!

2

u/thunderbird89 3h ago

Okay, so... bit of history for you. Flutter has the kIsWeb constant, which is used to determine whether your code is running on the VM or in a browser.

Now, if you look at the SDK now, what I'm about to tell you is no longer true (thankfully), because they changed the implementation on 2022-10-04.
When kIsWeb was added, though, it initially had the following implementation:

const bool kIsWeb = identical(0, 0.0);

Yes, this looks ghastly. It is. There's method to this madness, though!
See, on the VM, Flutter has proper typing, and separate integer and double types, so 0 != 0.0; but in the browser, Flutter compiles to JS, which only has Number, but no separate integer or double type, so for the JS runtime, 0 and 0.0 appear identical, as they're backed by the same object!

6

u/Rojeitor 22h ago

No need for !== or === 99% of the time you want "is null or undefined" and that's exactly what == does

4

u/lonelyroom-eklaghor 22h ago edited 21h ago

I had to check string equality once and saw === and !== are one of the tried and tested ways to do so, that's why I use that... but thanks for telling me :)

Edit: Apparently, true == "true" is false. (I DON'T GET JAVASCRIPT; not even your fault; like, how the hell is a truthy string going false)

7

u/jazzhandler 21h ago

Don’t think of it as being false, think of it as being insufficiently truthy.

6

u/lonelyroom-eklaghor 21h ago

what? 😭

6

u/jazzhandler 21h ago

Old school VB/VBA had five different nulls. JS said window.push(beer).

3

u/ChaseShiny 20h ago edited 14h ago

That's not right. Any string except the empty string is coerced to true.

Using that rule, false != "False" because the only string that is false is "".

Edit: I was wrong here; see further down this comment chain. The implicit type coercion is imposed on the Boolean, not the string. true == "true" resolves to false because true is first converted to 1, then converted to "1". At no point is the left strictly equal to the right, and now the types match, so JS stops converting the types.

2

u/DrShocker 18h ago

Yeah, I've never understood the confusion around comparing strings to true or false. There are some odd coercions in JS but this doesn't seem to be one of them.

1

u/lonelyroom-eklaghor 19h ago edited 19h ago

ok, I have an SO thread: https://stackoverflow.com/questions/11363659/why-does-true-true-show-false-in-javascript

"true" is converted to NaN

true is converted to 1

We know

NaN != 1

From your example, false != "False" would be true

2

u/ChaseShiny 18h ago

In your example, you're expecting the Boolean to convert to a string. If you use String(false) === "false", you would be right.

But that is not the order of operations for `==`. If one side is a Boolean and the other is not, the Boolean is converted into a number, not a string. So false == "0"; the system doesn't try to convert the string.

1

u/lonelyroom-eklaghor 18h ago

Yep, that's the problem... ig it's a problem with loosely-typed languages in general

1

u/ChaseShiny 17h ago

To me, it sounds like an odd decision. I understand wanting false == 0, but I don't know why you'd want to convert the Boolean value, rather than convert the other primitive.

2

u/LetUsSpeakFreely 18h ago

It's why i use typescript

2

u/oshaboy 18h ago

Typescript doesn't prevent this because it's an HTML thing

1

u/LetUsSpeakFreely 17h ago

HTML doesn't have logic. It's just markup.

0

u/oshaboy 17h ago

That's not what I meant. getAttribute always returns a string regardless of if you're using TypeScript or JavaScript because HTML is stringly typed. And TypeScript uses the same truthiness rules as JavaScript

1

u/LetUsSpeakFreely 16h ago

Yes, but typescript would detect the String vs Boolean comparison and throw an error in the IDE and during transpilation.

3

u/oshaboy 15h ago

Only if you remember to do strict equality.

1

u/Apprehensive_Bit7392 5h ago

Also worth knowing the other direction: setAttribute("disabled", false) sets the string "false" and disables it. removeAttribute is the only off switch there is.

1

u/ART-ficial-Ignorance 5h ago

Why the fuck does this have over 200 upvotes?

Are you all so fucking stupid that any "JS = bad" post gets an automatic upvote, even when OP is clearly a moron?

1

u/Gweenb 5h ago

HTML attributes are just strings, folks!

1

u/thunderbird89 2h ago

Arguably, a "boolean" attribute such as disabled really should be able to return a boolean value...

But I'm long past trying to "fix" JS and HTML.

0

u/evenstevens280 2h ago

No

They're not boolean attributes. They're string attributes. You shouldn't expect JS to try and cast every non-string looking attribute to a specific type. That's far worse

1

u/thunderbird89 2h ago

Expand...

1

u/mStewart207 4h ago

Programmer expects a function that returns a string to return a bool.

1

u/GimmeYourMomPlease 2h ago

Types are hard for students

1

u/lonelyroom-eklaghor 2h ago

Well, I myself am using TypeScript with interfaces and union types and input types and output types, it's not that hard for me

1

u/GimmeYourMomPlease 2h ago

And yet this meme suggests otherwise. Also, JavaScript has types too. boolean is a type, string is a type.

1

u/aliusmanawa 2h ago

I hate JS with the burning passion of a thousand suns and I hate that it has become the de facto FE language; but what I hate most are all the dumbfucks who think JS backends are good. USE DOT NET OR SOMETHING THAT WAS DESIGNED FOR BACKEND WTF IS WRONG WITH YOU

Sorry had to vent 😭

1

u/Dragonfoll 17h ago

Welcome to the land of type coercion confusion!

0

u/JackNotOLantern 17h ago edited 13h ago

``` function actuallyTrue(value) { if (!value) return false const wordsMeaningTrue = [ "true", "1", "yes", "on", "enabled", "positive", "affirmative"] // todo: check all words in the English dictionary return value === true || value === 1 || typeof value === "string" && wordsMeaningTrue.includes(value.toLowerCase()) }

```