Mona Abdelmajeed
Mona Abdelmajeed

Reputation: 686

Get tag name from its attribute name

I have an array like this:

["school_name":"My School Name", "school_number":"54546", "note":"", "class":1]

and HTML like this:

<input type="text" name="school_name" />
<input type="text" name="school_number" />
<textarea name="note" ></textarea>
<select name="class">
    <option value="1"> One </option>
    <option value="2"> Two </option>
    <option value="3"> Three </option>
</select>

I want to get a tag's name from its attribute name:

$('*[name=school_name]').attr("tag"); // this is input
$('*[name=class]').attr("tag"); // this is select
$('*[name=note]').attr("tag"); // this is textarea

Note that I have tried this:

$('*[name=school_name]').attr("tag");
$('*[name=school_name]').prop("tag");
$('*[name=school_name]').get(0).tagName;
$('*[name=school_name]')[0].tagName;

This is what I want to do:

If the tag name is input text,

$("input[name=school_name]").attr("value", "My School Name");

If the tag name is a select box,

$("select[name=class]").children("option[value=2]").attr("selected", "selected");

Upvotes: 1

Views: 570

Answers (5)

creemama
creemama

Reputation: 6665

var schoolProperties = {
    "school_name": "My School Name",
    "school_number": "54546",
    "note": "",
    "class": 1
};
for (var property in schoolProperties) {
    $('*[name=' + property + ']').attr('value', schoolProperties[property]);
}

​This is demonstrated in this fiddle.

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68400

If I got what you're looking for then you need to use filter

$('[name=school_number]').filter("input");
$('[name=class]').filter("select");
$('[name=note]').filter("textarea");

Upvotes: 2

Paul
Paul

Reputation: 141827

You had the correct way to do it. Both of these work:

$('*[name=school_name]').get(0).tagName;
$('*[name=school_name]')[0].tagName;

You can also remove the * and you may want to convert the tagName to lowercase first or at least a consistent case:

var $el = $('[name=school_name]');
var tagName;
if($el.length)
    tagName = $el[0].tagName

if(tagName)
    tagName = tagName.toLowerCase();

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78530

You can use the attribute .nodeName to determine the tag name of an element

Upvotes: 1

Jeff Watkins
Jeff Watkins

Reputation: 6359

As of jQuery 1.6, you want to use $xxxxx.prop("tagName")

Upvotes: 1

Related Questions