Is there a way in jQuery to determine whether an element has a value or innerhtml (or both)? For example, if the element is input then it has a val and I can use:
$(this).val();
But if it's a div then I need to use:
$(this).html();
I need to know whether I have to use val or HTML. My piece of jQuery is:
$(".myclass").each(function(idx){
  if (this is a val based element)
    use val
  else
    use html
});
                Try this fiddle.
Html:
<div></div>
<input/>
<textarea></textarea>
<select>
    <option>foo</option>
    <option>baz</option>
</select>
Code:
changeText("div", "baz");
changeText("input", "baz");
changeText("textarea", "baz");
changeText("select", "baz");
function changeText(selector, text) {
    var element = $(selector);
    var attr = element.attr('value');
    if (typeof attr !== 'undefined' && attr !== false) {
        element.val(text);
    } else {
        element.text(text);        
    }
}
                        $(".myclass").each(function(k, v){
    var data = ($(v).val() ?: $(v).html());
});
Try to get data from .val(), if nothing was returned use .html().
this.tagName will tell you which element type you have. jQuery object doesn't have tagName property.
This should do the trick:
See DEMO
$(".myclass").each(function(idx){
    if (this.hasOwnProperty('value'))
        //use val
    else
        //use html
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With