0

From what I learnt in JS it's possible to use document.getElementById to get access to manipulate tag.

But since I started using objects, I don't see how is it possible to connect object with for example <div>'s id.

So to be clear if I have <div id="box"></div> and then in JS document: var x = document.getElementById("box"); I can use x to manipulate that div. That is all clear, but when I try something like this:

var x ={}; and then put methods inside object, how to set this x to be able to manipulate <div>?

I hope I was clear. :)

Leverquin
  • 1
  • 2
  • You already have a variable `x` containing a reference to your object, and you can just call methods on that: `x.method()`. There is no need for `getElementById` or stuff, which is **only** for *DOM elements*. – Bergi Mar 20 '16 at 16:42
  • Do you mean `var X={ box:document.getElementByIs("box") , ....}`. And X.box.something – mplungjan Mar 20 '16 at 16:42
  • 2
    Nol, you weren't clear. First off, `var x {};` is a syntax error. Second, describe *what* you want to do, not how you are trying to do it. – Tomalak Mar 20 '16 at 16:42
  • 1
    http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – mplungjan Mar 20 '16 at 16:46
  • indeed i made syntax error, I meant var x = {}; I wanted to make one object with methods instead of have var and functions. – Leverquin Mar 20 '16 at 16:50

1 Answers1

1

Everything is object. Well, almost.. getElementById() returns object, so you can modify it properties as your wish:

var x = document.getElementById("div1");
x.newFunc = function() {
  this.innerHTML = "some string";
};
x.newFunc();
Slava N.
  • 596
  • 4
  • 6
  • What do you mean by "almost"? – Wiktor Zychla Mar 20 '16 at 17:11
  • `null` is not an object, for example. Other primitives aren't, either, until boxed (for example, `3` is not an object until auto-boxing turns it into a `Number` instance). – Tomalak Mar 20 '16 at 17:14
  • `null` is tricky :), typeof(null) results in 'object', but it is not. And definetly other primitives: number, boolean, string, undefined - are not objects. – Slava N. Mar 20 '16 at 17:22
  • My comment was supposed to provoke you to provide this additional explanation. I guess most people perfectly know what is and what isn't an object, however you used an unfortunate word "everything" without giving such informative context to it. – Wiktor Zychla Mar 20 '16 at 17:58