2

Can someone explain why this won't work?

var element = document.getElementById('element'); // Works OK
var slide = element.getElementById('slide'); // Throws an error

So the idea is to fetch DOM only once, and I have all the tags in that one variable, and then I can manipulate it and get the rest from that variable.

How can I get other elements from element variable? Is it a bad thing to use document.getElementById('id'); every time I need something from the DOM? Does it slows down webpage?

And how would I solve this problem?

No jQuery please, pure Javascript!

Thanks

4 Answers4

3

Element doesn't have getElementById method, document has,

so use

document.getElementById('slide');
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

you are trying to get an element by its id. so it doesn't matter if it's nested inside elements or it's a parent element! because no more than one element in the DOM can have the same ID.

same as getting the first element you have to use:

document.getElementById('slide');

instead of:

element.getElementById('slide');

because element variable doesn't have the method getElementById. you get that from document object.

0

document.getElementById('element'); will get you the control with specific ID from your DOM. So, for getting control with id slide as well you will have to use the document object

document.getElementById('slide');
Rahul
  • 76,197
  • 13
  • 71
  • 125
0
Element.prototype.getElementById = function(req) {
    var elem = this, children = elem.childNodes, i, len, id;

    for (i = 0, len = children.length; i < len; i++) {
        elem = children[i];

        //we only want real elements
        if (elem.nodeType !== 1 )
            continue;

        id = elem.id || elem.getAttribute('id');

        if (id === req) {
            return elem;
        }
        //recursion ftw
        //find the correct element (or nothing) within the child node
        id = elem.getElementById(req);

        if (id)
            return id;
    }
    //no match found, return null
    return null;
}

So you can use this code

var element = document.getElementById('element'); // Works OK
var slide = element.getElementById('slide'); // Will work

From answer for another question

Community
  • 1
  • 1
Taleh Ibrahimli
  • 750
  • 4
  • 13
  • 29