-3

I have set of html elements and I named those for all input/select/textarea. Anyway the names are unique for each element.

Now I need to get the Html TAG (Input/Select/Textarea) by Element name.

For EX:

<input type="text" name="sample" />

I need to get the 'input' TAG by using element name 'sample'.

I dont want to mention the TAG name on selector part in jquery. I have only unique names to find the TAGs.

Please help on this.

Thanks in advance.!

Karthik Rajan
  • 164
  • 1
  • 15

5 Answers5

2

use querySelector() to retrieve the element and tagName to retrieve the tag name

document.querySelector('[name="sample"]').tagName.toLowerCase();

Codepen demo

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

You should be able to select them with the tag name and then the name attribute like this: $('input[name="sample"]')

$('input[name="sample"]').val('Lorem Ipsum');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="sample" />
1

You can use .tagName

console.log(document.querySelector('[name=sample]').tagName);
<input type="text" name="sample" />
Phiter
  • 14,570
  • 14
  • 50
  • 84
  • No. Javascript is also okay for me. I am happy with this code. Thanks. – Karthik Rajan Feb 02 '18 at 14:17
  • 1
    ps. If you wanted to do this with a jQuery selector, you can do this -> `$('[name="sample"]').each((r,el) => console.log(el.tagName));` – Keith Feb 02 '18 at 14:22
1

In jquery you can do this:

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

This will select the element you want.

If you want to do it in native js you would do this:

var x = document.getElementsByName("attribute name");

That will return an array, and in your case, you would have only one element in it, so the element you need would be x[0].

Bojan Ivanac
  • 1,170
  • 8
  • 17
0

Use this:

$('input[name="name_of_element"]')

same goes with select, textarea, etc.

molinet
  • 266
  • 3
  • 14