Get element inside element by class and ID – JavaScript

Well, first you need to select the elements with a function like getElementById. var targetDiv = document.getElementById(“foo”).getElementsByClassName(“bar”)[0]; getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that’s what the [0] … Read more

chaining getElementById

Nope. …But you can, though: Element.prototype.getElementById = function(id) { return document.getElementById(id); } Try it on this page: var x = document.getElementById(‘footer’).getElementById(‘copyright’); Edit: As Pumbaa80 pointed out, you wanted something else. Well, here it is. Use with caution. Element.prototype.getElementById = function(req) { var elem = this, children = elem.childNodes, i, len, id; for (i = 0, … Read more

How to use getElementsByClassName in javascript-function? [duplicate]

getElementsByClassName() returns a nodeList HTMLCollection*. You are trying to operate directly on the result; you need to iterate through the results. function change_boxes() { var boxes = document.getElementsByClassName(‘boxes’), i = boxes.length; while(i–) { boxes[i].style.backgroundColor = “green”; } } * updated to reflect change in interface

JavaScript getElementByID() not working [duplicate]

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this: <html> <head> <title></title> <script type=”text/javascript”> window.onload = function(){ var refButton = document.getElementById(“btnButton”); refButton.onclick = function() { alert(‘I am … Read more

Getting the parent div of element

You’re looking for parentNode, which Element inherits from Node: parentDiv = pDoc.parentNode; Handy References: DOM2 Core specification – well-supported by all major browsers DOM2 HTML specification – bindings between the DOM and HTML DOM3 Core specification – some updates, not all supported by all major browsers HTML5 specification – which now has the DOM/HTML bindings … Read more