Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery equivalent to "getElementsByName"

What is the correct jquery syntax for a getElementsByName call?

Here is my javascript code:

var test = document.getElementsByName(tableName)[0];

using this is returning a different value:

var test = $("[name=tableName]");

Thanks in advance

like image 704
user1258430 Avatar asked Mar 14 '12 23:03

user1258430


People also ask

How to get all elements with same name in jQuery?

You can use the Attribute Equals Selector ( [name='value'] ) to select elements with the given name in jQuery. Note, this might return more than one element since one can apply the same name to multiple elements within the document.

Is there a getElementsByName?

The getElementsByName() method returns a collection of elements with a specified name. The getElementsByName() method returns a live NodeList.

How to select element by name JavaScript?

Use the querySelector() method to get an element by a name attribute, e.g. document. querySelector('[name="first_name"]') . The method returns the first element in the DOM that matches the provided selector. If no element matches the selector, null is returned.


2 Answers

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);
like image 94
zzzzBov Avatar answered Sep 30 '22 08:09

zzzzBov


Remove the index from the first statement

These are equal.

var test = document.getElementsByName(tableName);
var test = $("[name=tableName]");
like image 20
westo Avatar answered Sep 30 '22 09:09

westo