-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?

10
  • 2
    You are stuck with it. Jquery has an easier way Commented Jan 21, 2019 at 12:05
  • 4
    Possible duplicate of Use of document.getElementById in JavaScript Commented Jan 21, 2019 at 12:07
  • 2
    Use a code editor with auto complete, also helps prevent mistakes in your code if typing isn't your thing. Commented Jan 21, 2019 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. Commented Jan 21, 2019 at 12:12
  • 2
    @Sujit - More accurately, this is the DOM for you. getElementById isn't JavaScript method. Commented Jan 21, 2019 at 12:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thats not exactly answer see they wants smaller in size of answer but you gave more long as he want.
@RitulLakhtariya - example and gid("example") are both clearly shorter than document.getElementById("example").
0

You can use jQuery to get the element by id

eg:

$("#example"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.