DOM getElementsByTagName within a given class, getting all the elements with a certain tag that are within an element |
DOM getElementsByTagName within a given class, getting all the elements with a certain tag that are within an element |
Jonathan Stegall |
Jan 4 2008, 11:47 AM
Post
#1
|
Group: Members Posts: 1 Joined: 4-January 08 Member No.: 4,641 |
Hello,
I've been looking around for a way to do this, and haven't found one yet. Here's the scenario: I know that it's possible to do the following: CODE var parent = document.getElementByID("someid"); var child = parent.getElementsByTagName("p"); And then to interact with child elements in whatever way one desires. Like many people, I use the following function to get an array of elements that have a given class: CODE function getElementsByClassName(className, tag, elm){ var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)"); var tag = tag || "*"; var elm = elm || document; var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag); var returnElements = []; var current; var length = elements.length; for(var i=0; i<length; i++){ current = elements[i]; if(testClass.test(current.className)){ returnElements.push(current); } } return returnElements; } So, what I'd like to do is essentially this: CODE var parent = getElementsByClassName("myclass"); var child = parent.getElementsByTagName("p"); And then to have the ability to interact with child in the same way that I could in the other example. I thought this would work, but apparently getElementsByClassName doesn't return the items in the same way that getElementByID does, because I can't use the result as a parent. Does anyone know a way to do this? Thanks so much, Jonathan |
Lo-Fi Version | Time is now: 19th April 2024 - 06:27 PM |