[javascript] How can I select an element by name with jQuery?

Have a table column I'm trying to expand and hide:

jQuery seems to hide the td elements when I select it by class but not by element's name.

For example, why does:

$(".bold").hide(); // selecting by class works
$("tcol1").hide(); // select by element name does not work

Note the HTML below, the second column has the same name for all rows. How could I create this collection using the name attribute?

<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2</td>
</tr>  
<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2</td>
</tr>

The answer is


If you have something like:

<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

You can read all like this:

jQuery("input[name='mycheckbox']").each(function() {
    console.log( this.value + ":" + this.checked );
});

The snippet:

_x000D_
_x000D_
jQuery("input[name='mycheckbox']").each(function() {_x000D_
  console.log( this.value + ":" + this.checked );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="mycheckbox" value="11" checked="">_x000D_
<input type="checkbox" name="mycheckbox" value="12">
_x000D_
_x000D_
_x000D_


Performance

Today (2020.06.16) I perform tests for chosen solutions on MacOs High Sierra on Chrome 83.0, Safari 13.1.1 and Firefox 77.0.

Conclusions

Get elements by name

  • getElementByName (C) is fastest solution for all browsers for big and small arrays - however I is probably some kind of lazy-loading solution or It use some internal browser hash-cache with name-element pairs
  • mixed js-jquery solution (B) is faster than querySelectorAll (D) solution
  • pure jquery solution (A) is slowest

Get rows by name and hide them (we exclude precalculated native solution (I) - theoretically fastest) from comparison - it is used as reference)

  • surprisingly the mixed js-jquery solution (F) is fastest on all browsers
  • surprisingly the precalculated solution (I) is slower than jquery (E,F) solutions for big tables (!!!) - I check that .hide() jQuery method set style "default:none" on hidden elements - but it looks that they find faster way of do it than element.style.display='none'
  • jquery (E) solution is quite-fast on big tables
  • jquery (E) and querySelectorAll (H) solutions are slowest for small tables
  • getElementByName (G) and querySelectorAll (H) solutions are quite slow for big tables

enter image description here

Details

I perform two tests for read elements by name (A,B,C,D) and hide that elements (E,F,G,H,I)

  • small table - 3 rows - you can run test HERE
  • big table - 1000 rows - you can run test HERE

Snippet below presents used codes

_x000D_
_x000D_
//https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery#

// https://jsbench.me/o6kbhyyvib/1
// https://jsbench.me/2fkbi9rirv/1

function A() {
  return $('[name=tcol1]');
}

function B() {
  return $(document.getElementsByName("tcol1"))
}

function C() {
  return document.getElementsByName("tcol1")
}

function D() {
  return document.querySelectorAll('[name=tcol1]')
}

function E() {
  $('[name=tcol1]').hide();
}

function F() {
  $(document.getElementsByName("tcol1")).hide();
}

function G() {
  document.getElementsByName("tcol1").forEach(e=>e.style.display='none'); 
}

function H() {
  document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none'); 
}

function I() {
  let elArr = [...document.getElementsByName("tcol1")];
  let length = elArr.length
  for(let i=0; i<length; i++) elArr[i].style.display='none';
}




// -----------
// TEST
// -----------

function reset() { $('td[name=tcol1]').show(); } 

[A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`)) ;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>This snippet only presents used codes</div>
<table>
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>  
  <tr>    
      <td>data1</td>
      <td name="tcol1" class="bold"> data2</td>
  </tr>
</table>

<button onclick="E()">E: hide</button>
<button onclick="F()">F: hide</button>
<button onclick="G()">G: hide</button>
<button onclick="H()">H: hide</button>
<button onclick="I()">I: hide</button><br>
<button onclick="reset()">reset</button>
_x000D_
_x000D_
_x000D_

Example results on Chrome

enter image description here


You can get the element in JQuery by using its ID attribute like this:

$("#tcol1").hide();

You can get the name value from an input field using name element in jQuery by:

_x000D_
_x000D_
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
  <input type="text" name="firstname" value="ABCD"/>_x000D_
  <input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_


Frameworks usually use bracket names in forms, like:

<input name=user[first_name] />

They can be accessed by:

// in JS:
this.querySelectorAll('[name="user[first_name]"]')

// in jQuery:
$('[name="user[first_name]"]')

// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

You can use any attribute as selector with [attribute_name=value].

$('td[name=tcol1]').hide();

You can use the function:

get.elementbyId();

You could get the array of elements by name the old fashioned way and pass that array to jQuery.

_x000D_
_x000D_
function toggleByName() {_x000D_
  var arrChkBox = document.getElementsByName("chName");_x000D_
  $(arrChkBox).toggle();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>sandBox</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <input type="radio" name="chName"/><br />_x000D_
    <input type="radio" name="chName"/><br />_x000D_
    <input type="radio" name="chName"/><br />_x000D_
    <input type="radio" name="chName"/><br />_x000D_
    <input type="button" onclick="toggleByName();" value="toggle"/>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

note: the only time you would have a reason to use the "name" attribute should be for checkbox or radio inputs.

Or you could just add another class to the elements for selection.(This is what I would do)

_x000D_
_x000D_
function toggleByClass(bolShow) {_x000D_
  if (bolShow) {_x000D_
    $(".rowToToggle").show();_x000D_
  } else {_x000D_
    $(".rowToToggle").hide();_x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>sandBox</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>data1</td>_x000D_
        <td class="bold rowToToggle">data2</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>data1</td>_x000D_
        <td class="bold rowToToggle">data2</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>data1</td>_x000D_
        <td class="bold rowToToggle">data2</td>_x000D_
      </tr>_x000D_
    </table>_x000D_
    <input type="button" onclick="toggleByClass(true);" value="show"/>_x000D_
    <input type="button" onclick="toggleByClass(false);" value="hide"/>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Any attribute can be selected using [attribute_name=value] way. See the sample here:

var value = $("[name='nameofobject']");

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

I've done like this and it works:

$('[name="tcol1"]')

https://api.jquery.com/attribute-equals-selector/


Here's a simple solution: $('td[name=tcol1]')


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to jquery-selectbox

How to check whether a select box is empty using JQuery/Javascript jQuery Set Select Index jQuery Set Selected Option Using Next Hide options in a select list using jQuery jQuery to retrieve and set selected option value of html select element Counting the number of option tags in a select tag in jQuery How can I select an element by name with jQuery? jQuery add blank option to top of list and make selected to existing dropdown jQuery: Selecting by class and input type Selecting option by text content with jQuery