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

2
  • 1
    can you show the whole html page Commented Jan 31, 2016 at 9:14
  • Possible duplicate of chaining getElementById Commented Jan 31, 2016 at 9:15

4 Answers 4

3

Element doesn't have getElementById method, document has,

so use

document.getElementById('slide'); 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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'); 

Comments

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

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.