Reputation: 1
i need a clarification regarding my bug.
my requirement is to get the html tag names used in UI dynamically using javascript. Where my code got executed in IE, but it's not proper in Mozila Firefox. My Code,
HTML CODE:
<table>
<tr>
<td>
<input type="text" />
</td>
<td>
<select>
<option>p_string1</option>
<option>p_string5</option>
</select>
</td>
</tr>
</table>
JS:
for (i = 0; i < table.rows[0].cells.length; i++)
{
pNode[i] = table.getElementsByTagName('td')[i].childNodes[0].nodeName;
}
I'm getting the value #text
instead of the tag name Select
. But getting the tagname INPUT
properly..
Upvotes: 0
Views: 60
Reputation: 5888
I would assume this is because firefox (correctly) selects the first childNode, which is whitespace. If you remove ALL white space between the and the you'd probably get the correct tag.
EDIT, like this:
<td><input
I created some jsFiddles to demonstrate the effect:
EDIT 2:
You could consider using document.querySelectorAll
. This is support in all browsers except IE6 and IE7. If you don't need support for these, something like this might work.
var inner_tags = document.querySelectorAll('td > *')
var first_tag = inner_tags[0].tagName;
Hope this helps.
Upvotes: 2
Reputation: 1811
use the tagName and firstChild element attributes:
http://www.w3schools.com/jsref/prop_element_tagname.asp
var cells = table.getElementsByTagName('td');
for (i = 0; i < table.rows[0].cells.length; i++)
{
var cell = cells[i];
if ( cell && cell.firstChild) {
result = null;
for ( position in cell.childNodes){
if (! result) result = cell.childNodes[position].tagName;
}
pNode[i] = result;
}
}
Notice that line hops and tabulation are noticed by some browsers as TextNodes, which have not tagName, because of that we cycle through the childnodes searching for a defined tagName attribute. I updated the example at http://jsfiddle.net/9YJsd/1/
Upvotes: 0