JQuery - How to define between val and HTML?

Is there a way in jQuery to determine if an element has a value or innerhtml (or both)? For example, if an element is entered, then it has a value of val, and I can use:

$(this).val(); 

But if it is a div, I need to use:

 $(this).html(); 

I need to know if I need to use val or HTML. My jQuery part:

 $(".myclass").each(function(idx){ if (this is a val based element) use val else use html }); 
+4
source share
5 answers

this.tagName will tell you what type of item you have. The jQuery object does not have a tagName property.

+1
source

Try 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); } } 
+5
source
 $(".myclass").each(function(k, v){ var data = ($(v).val() ?: $(v).html()); }); 

Try to get data from .val (), if nothing was returned, use .html ().

+2
source

This should do the trick:

See DEMO

 $(".myclass").each(function(idx){ if (this.hasOwnProperty('value')) //use val else //use html }); 
+1
source

Verify that it has a value attribute

 if ($(this).hasAttr('value')){ } 
0
source

All Articles