Differentiate types of HTML elements in JavaScript or jQuery

Question:

I have a series of labels in my JSP view. Each label shows a unit of measure and if you want to edit it, it is replaced via javascript by an input via button.

NOTE: both labels and inputs are elements with class = "CCC_UNIDAD" to be iterated later. The resulting simplified html would look something like this:

<label class="CCC_UNIDAD">%</label>
<input class="CCC_UNIDAD">
<input class="CCC_UNIDAD" value="$">
<label class="CCC_UNIDAD">€</label>

$.each($(".CCC_UNIDAD"), function (index, value) {
    var valor = value.textContent === undefined 
                                  ? (value.value === undefined ? "" : value.value) 
                                  : value.textContent; 
    alert("VALOR = " + valor);
});

As you can see, in the snippet, I try to get the value of the label ( value.textContent ), if it does not have it I look for the value of the input value.value but it is not working correctly.

How can I differentiate what type of element is the value variable in order to get the attribute corresponding to each type?

Answer:

First of all as @rnrneverdies mentions the HTML is not well formed. The input tags do not have a closing tag but are self-closing.

The correct form should be:

<label class="CCC_UNIDAD">%</label>
<input class="CCC_UNIDAD" value=""/>
<input class="CCC_UNIDAD" value="$" />
<label class="CCC_UNIDAD">€</label>

Then to get the value or the text you can use the operator ||

$(".CCC_UNIDAD").each(function(){
    alert("VALOR = " + ($(this).val() || $(this).text()));
});

Finally in your case everything would be like the following snippet

$("button").click(function(){
    $(".CCC_UNIDAD").each(function(){
        alert("VALOR = " + ($(this).val() || $(this).text()));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label class="CCC_UNIDAD">%</label>
<input class="CCC_UNIDAD" value=""/>
<input class="CCC_UNIDAD" value="$" />
<label class="CCC_UNIDAD">€</label>	
<button>Hazme clic me para probar</button>
Scroll to Top