J
J
Javarast Skriptovich2018-11-08 12:17:25
JavaScript
Javarast Skriptovich, 2018-11-08 12:17:25

What is the best way to access an element by id?

There are three options for addressing:
1) The old fashioned way 2) Symbolic and economical
document.getElementById('КакойТоАйДи').метод;

'use strict'; // Включаем прогрессивизм
let ID=t=>document.getElementById(t); // Декоратор дефолтного сатанинского синтаксиса
...
ID('КакойТоАйДи').метод; // собсна, обращение к элементу

3) Magic-implicit
КакойТоАйДи.метод;
1st Option generates kilometers of code, but the fastest (but this is not accurate)
2nd Strongly reduces the number of characters in the file, but it is not known how fast
3rd Extremely minimalistic, but just implicit (is it a custom object? a variable?)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-11-08
@M4mkin_pr0ger

const $ = selector => document.querySelectorAll(selector)
$('#hello .world').forEach(...)

Pros: short, works not only with id but also with any css selectors
Cons: can blow someone up, because it looks too much like jQuery :)
But you can use a different symbol
It is often convenient to immediately convert to an array
const $ = selector => Array.from(document.querySelectorAll(selector))

T
tundramani, 2018-11-08
@tundramani

if there is only one such id in the document then:
getElementById
or just call directly:
id.remove()
the browser automatically creates the id variable in the global scope
if there are several such id then:
querySelectorAll( '#' + id)
and yes, there can be several id - it's not forbidden and sometimes it's convenient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question