How check for ID existence using jQuery?

后端 未结 4 1466
南笙
南笙 2021-01-17 07:24

I want to have a line of code similar to below:

var name = $(\'#input-name\').attr(\"value\");

However, the id \'input-name\' is not guaran

相关标签:
4条回答
  • 2021-01-17 07:43

    In my test the assignment didn't cause an error, it simply returned undefined.

    In which case the solution would be the following:

    var name = $('#input-name').attr("value");
    if (name) {
      // blah blah
    }
    

    Or maybe:

    var name = $('#input-name').attr("value") || 'defaultValue';
    

    ... if that makes sense in your case.

    0 讨论(0)
  • 2021-01-17 07:47
    if ($('#input-name').length) {
      // do something
    }
    
    0 讨论(0)
  • 2021-01-17 08:03

    Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.

    0 讨论(0)
  • 2021-01-17 08:03
    var name;
    if ($('#input-name').length > 0)   
    name= $('#input-name').attr("value");
    
    0 讨论(0)
提交回复
热议问题