-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.!

0

5 Answers 5

2

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

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

Codepen demo

Sign up to request clarification or add additional context in comments.

3 Comments

@Sankar: jQuery can't get the tag name. It has no API for that. It can select the elements, but you must ultimately abandon jQuery anyway, so why not altogether?
@fcalderan Thanks. Its working. ThankYou.
Downvotes for a vanillaJS lightweight and portable solution instead of jQuery? Really?
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" />

Comments

1

You can use .tagName

console.log(document.querySelector('[name=sample]').tagName);
<input type="text" name="sample" />

2 Comments

No. Javascript is also okay for me. I am happy with this code. Thanks.
ps. If you wanted to do this with a jQuery selector, you can do this -> $('[name="sample"]').each((r,el) => console.log(el.tagName));
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].

Comments

0

Use this:

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

same goes with select, textarea, etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.