views:

581

answers:

2

How can I use YUI to locate a text input by name and insert a div after it?

For example, this doesn't work:

<input name="some_name" type="text">

<script>
var el = new YAHOO.util.Element(document.createElement('div'));
var some_element = document.getElementsByName('some_name');

// doesn't work .... replacing 'some_element' with 'document.body' works
el.appendTo(some_element);

</script>
+1  A: 

document.getElementsByName('some_name') always return a collection (an Array), if you are sure that the name is unique you can safely write this.

var some_element = document.getElementsByName('some_name')[0];
SleepyCod
+3  A: 

As mentioned, document.getElementsByName returns an array. You may want to give your input an ID with the same name as the name attribute. (Aside: This is common and good practice for forms. Other js libraries provide helpful extensions when you do this.)

<input name="some_name" id="some_name" type="text">
<script>
(function () {
var el = new YAHOO.util.Element(document.createElement('div'));
// var some_element = document.getElementByName('some_name')[0];
var some_element = document.getElementsById('some_name'); // preferred, faster
// el.appendTo(some_element);
YAHOO.util.Dom.insertAfter(el,some_element);
})();
</script>

Also notice the use of insertAfter rather than appendTo. You do not want el to be a child of your input element. You want it to be the next sibling. Inputs do not have children. Also lastly, you're adding these variables to the global namespace. This may or may not be a problem, but it's generally a good idea to wrap your code in an anonymous function unless you intend for the variables to have global scope and reuse them later, but then you might want to provide a proper namespace for them.

Hope that helps (and not too much info.) ;)

Keith Bentrup
Yes, that works great. I opted not to use the getElementbyId option because I want to be able to locate several inputs with the same name (such as checkboxes). BTW there is a typo "getElementsById". The part I couldn't figure out on my own was: YAHOO.util.Dom.insertAfter(el,some_element);