0

In a dropdown I want to get a custom attribute from my options element:

<select name="t" id="t">
    <option value="all">- all -</option>
    <optgroup label="Europe">
        <option selected value="1" myAttr="1">Fr</option>
        <option value="2" myAttr="0">Uk</option>
    </optgroup>
    <optgroup label="America">
        <option value="3" myAttr="1">USA</option>
        <option value="4" myAttr="0">CA</option>
    </optgroup>
    <optgroup label="Asia">
        <option value="5" myAttr="0">JP</option>
    </optgroup>
</select>

So I first loop over optgroup tags, and then I loop over option one's (Fiddle).

var temp = document.getElementById("t").childNodes;
// Loop the optGroup
for (var i = 0; i < temp.length; i++) {
    // Loop the option
    for (var j = 0; j < temp[i].childNodes.length; j++) {

Then I want to test if my element is an HTMLOptionElement before getting my custom attribute, I tried some tips from this SO question, but without success, I always get 'undefined'. Is thhre a specific method to use with DOM elements?

Community
  • 1
  • 1
Fractaliste
  • 5,777
  • 11
  • 42
  • 86

3 Answers3

2

You need to use nodeName :

var div1 = document.getElementById("d1");
var div1Type = div1.nodeName;

And the difference between nodeName and tagName.

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
1

Element.tagName - Returns the name of the element.

peritus
  • 3,732
  • 2
  • 22
  • 17
1

Every DOM element has a tagName attribute that you can use: myChildNode.tagName

juanignaciosl
  • 3,435
  • 2
  • 28
  • 28