View Full Version : finding an element inside another

12 Jan 2007, 6:08 PM
I'm trying to find an item with a specific class inside of another.

I found YAHOO.util.Element.getChildrenByClassName.

I have a variable that contains an HTML Element:

How do I convert it to a YAHOO.util.Element so I can use getChildrenByClassName?

I tried:

//obj is an HTML element passed into this function

el = YAHOO.util.Element(obj);

Firebug tells me that YAHOO.util.Element is not a function.

Any idea what I'm doing wrong?
Is there a better way to find an item by className inside another?


12 Jan 2007, 7:15 PM
if obj is a string id, you can just getEl(obj). If it's a an object, for example from a document.getElementById(id) call, use getEl(obj.id)

You don't need to use the Element constructor.

12 Jan 2007, 7:47 PM
The object is an HTML element from the DOM tree but doesn't have an id as there are multiple of these (they have a common class). It returns null.
In order to make this work, do I need to auto create an ID?

I was hoping that I can just turn this HTML element into an ext.Element and thus get access to it's methods.


12 Jan 2007, 8:09 PM
Well in that case you can use the constructor, but it's
el = new YAHOO.ext.Element(obj), not YAHOO.util.Element. You need to create a yui-ext Element to be able to use the methods.

I would stay away from mixing the two, as you're just going to have headaches mixing the method names. Nothing in yui-ext use the YAHOO.util.Element

12 Jan 2007, 8:18 PM
YAHOO.util.Element is not a function, but YAHOO.ext.Element is. I think you are getting your namespaces mixed up. If you are starting with an HTML fragment and wanting to convert to an Element, getEl(obj) should return a YAHOO.ext.Element object, but I'm confused as to whether that's what you actually want or not.

This code example would find all DOM elements matching a classname and convert them into Ext elements:

var els = YAHOO.util.Dom.getElementsByClassName('foo');
for (var i = 0; i < els.length; i++) {
var el = getEl(els[i]);
//return an array of child YAHOO.ext.Elements matching a different class
var subEls = el.getChildrenByClassName('bar');
There's probably other ways to accomplish it, this is just an example. Better yet, you could live on the edge and give Jack's brand new selector library a try and get the above code down to a single call :)