-2

Is there any easier way to access element by it's Id than this long sentence?

    document.getElementById("example").innerHTML

It is very time consuming for me to write this whole sentence each time. Is there any better way to access an element in JavaScript?

Michael T
  • 370
  • 4
  • 16
  • 2
    You are stuck with it. Jquery has an easier way – ellipsis Jan 21 '19 at 12:05
  • take a function for it with a caching for the elements. – Nina Scholz Jan 21 '19 at 12:05
  • 4
    Possible duplicate of [Use of document.getElementById in JavaScript](https://stackoverflow.com/questions/19656581/use-of-document-getelementbyid-in-javascript) – Ritul Lakhtariya Jan 21 '19 at 12:07
  • 2
    Use a code editor with auto complete, also helps prevent mistakes in your code if typing isn't your thing. – Matthew Page Jan 21 '19 at 12:11
  • 1
    This is the Javascript for you! This is how it is. You may try other libraries built on top of the JS like jQuery or Lodash or something which might have a method shorter than the one you've mentioned. – Sujit Y. Kulkarni Jan 21 '19 at 12:12
  • 2
    @Sujit - More accurately, this is the DOM for you. `getElementById` isn't JavaScript method. – T.J. Crowder Jan 21 '19 at 12:13
  • 1
    The following is not considered best practice, but all `id` attribute values are used to create global variables, so you *could* in theory do: `example.innerHTML`, provided of course that you did not use that variable for other purposes. See [here](https://stackoverflow.com/a/3434388/5459839) for more details. – trincot Jan 21 '19 at 12:16
  • 1
    @RitulLakhtariya, The question you mentioned asks something entirely different. I asked if there is a shorter function or something, not why to add a

    .

    – Michael T Jan 21 '19 at 12:25

2 Answers2

6

In most cases, yes, but I wouldn't recommend it. Per the specification (and universally supported by browsers), elements in the DOM with id attributes show up as global variables with the id's value as their name. So you could use

example.innerHTML

But, the global namespace is crowded and there's a lot going on, with lots of potential for conflicts (for instance, id="name" doesn't make name refer to the element). Instead, give yourself a handy, reusable function:

function gid(id) {
    return document.getElementById(id);
}

It's also probably worth mentioning that relying on ids a lot tends to be a bit of an anti-pattern.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can use jQuery to get the element by id

eg:

$("#example");
Helenesh
  • 3,999
  • 2
  • 21
  • 36