https://unsplash.com/@sveninho

Get id, name, and class values using Javascript / jQuery

Last time, I tried to get each input value using id, name, and class.

 

This time we will use the id to get name/class, name to get id/class and class to get id and name.

(I do not remember exactly, sometimes you need them.)

 

Declare the div first.

<div id="test_id" class="test_class"></div>

One for using jQuery, the other for using the vanilla javascript.

 

Using jQuery.

 

By id

var name_by_id = $('#test_id').attr('name');
var class_by_id = $('#test_id').attr('class');

By class

var name_by_class = $('.test_class').attr('name');
var id_by_class = $('.test_class').attr('id');

By name

var id_by_name = $('[name="test_name"]').attr('id');
var class_by_name = $('[name="test_name"]').attr('class');

 

Using vanilla javascript 

(getElementById element is singular, class and name are plural)

By id

var name_by_id = document.getElementById("test_id").getAttribute('name');
var class_by_id = document.getElementById('test_id').ClassName;

By class

var name_by_class = document.getElementsByClassName('test_class')[0].getAttribute('name');;
var class_by_class = document.getElementsByClassName('test_class')[0].id;

By name

var id_by_name = document.getElementsByName('test_name')[0].id;
var class_by_name = document.getElementsByName('test_name')[0].className;

 

That’s it.

* If you use duplicate class or name, you should pay attention to set index value.