Monday, May 20, 2024
185
rated 0 times [  191] [ 6]  / answers: 1 / hits: 18862  / 12 Years ago, sun, december 16, 2012, 12:00:00

I'm using custom tags to define sections in an application, so I have something like this:



<mysection>

<form>
<input name=myfield>
</form>

</mysection>


I'm using the following and able to get the tag (printed to console, everything is groovy)



var parent = document.getElementsByTagName('mysection');


The issue I'm having is finding the child field by name:



var myfield = parent.getElementsByName(myfield);


...as I don't want to pick up on any other 'sections' that might have an input with the name 'myfield'.



EDIT:



var parent = document.getElementsByTagName('mysection')[0];


was suggested and returns to console the section contents, however, getElementsByName throws an error:



Uncaught TypeError: Object #<NodeList> has no method 'getElementsByName' 

More From » getelementsbyname

 Answers
66

Using getElementsByTagName() and getElementsByName() will return a NodeList, you need to get the first element of the list like this:



var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName(myfield)[0];


Edit



You were correct, getElementsByName is not valid for an element. I am unsure how to localize the functionality of it as you are trying to do. It seems that it will only work for document. You may have to write your own implementation of getElementsByName if you want to use it in a localized scope.



Second Edit



To be nice, I made that implementation for you :D Here it is in all its glory.



Element.prototype.getElementsByName = function (arg) {
var returnList = [];
(function BuildReturn(startPoint) {
for (var child in startPoint) {
if (startPoint[child].nodeType != 1) continue; //not an element
if (startPoint[child].getAttribute(name) == arg) returnList.push(startPoint[child]);
if (startPoint[child].childNodes.length > 0) {
BuildReturn(startPoint[child].childNodes);
}
}
})(this.childNodes);
return returnList;
};
var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName(myfield)[0];


Small fix



I was incorrectly passing the element and not its children into the recursion. The code above has been edited with the proper argument passed now. See working fiddle: http://jsfiddle.net/js6NP/5/


[#81388] Friday, December 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;