jQuery equivalent to “getElementsByName”

后端 未结 5 643
一生所求
一生所求 2020-12-25 14:07

What is the correct jquery syntax for a getElementsByName call?

Here is my javascript code:

var test = document.getElementsByName(tableN         


        
相关标签:
5条回答
  • 2020-12-25 14:55

    "[name=tableName]" is bad syntax in 2 ways. First, you should put your name in quotes, so it should be "[name='tableName']" and second, in the first case, you're using a variable and in the second, a string, so in reality it shoudl be "[name='" + tableName + "']"

    good call also on the fact that you have an index on your getelementsbyname() call, if you select item [0] then it will only return one item.

    0 讨论(0)
  • 2020-12-25 14:59

    Interesting to know that jquery is a LOT slower than the native method here. See the jsPrefs test : http://jsperf.com/getelementsbyname-vs-jquery-selektor/4

    0 讨论(0)
  • 2020-12-25 15:05

    Remove the index from the first statement

    These are equal.

    var test = document.getElementsByName(tableName);
    var test = $("[name=tableName]");
    
    0 讨论(0)
  • 2020-12-25 15:06

    Use quotes around the attribute selector:

    $('[name="somenamehere"]');
    

    If you need to use a variable within a selector, you need to use string concatenation to get the value of the variable:

    $('[name="' + tableName + '"]');
    

    Typically one should avoid using the [name] attribute in favor of the [id] attribute, because selection would be simpler as:

    $('#someidhere');
    -or-
    $('#' + tableID);
    
    0 讨论(0)
  • 2020-12-25 15:09

    if you want to get a element value use this code:

    var test1 = $("[name='tableName']").val();
    alert(test1);
    

    These are equal to get value of specific index[]:

    For same index [0]

    var test2 = $("[name='arryname[]']")[0];
    alert(test2.value);
    
    var test3 = $("[name='arryname[]']").get([0]);
    alert(test3.value);
    
    0 讨论(0)
提交回复
热议问题