Pablo Pablo - 3 months ago 11
JSON Question

Filtering elements by tagName

Example Fiddle.

I need to add conditions so my code support inputs (1 button need to generate the whole Json).

I've tried filtering with :

elements.tagName


But it gives me an undefined, I suppose it is because

var elements = document.getElementsByClassName('selectVal');


Returns a nodelist. How can I filter or adapt my code so the same function supports inputs?

I need to storage the selected item in list and the strings in the inputs just with one button.

Answer

elements is the array of elements you get from getElementsByClassName. You should check tagName on elements[index] inside the loop instead.

Add the input (replace the selectVal with a better class to all form objects though):

<input id="textbox" class="selectVal" value="text value">

You can change the inner part of the loop to look for the tag

...
var strSel = '';
if (element.tagName == 'select')
    strSel = element.options[element.selectedIndex].text;
else if (element.tagName == 'input')
    strSel = element.value;
...