3

Is there a way to get multiple attributes in jQuery

 <input type="text" title="hello there" class="maiz"/>


(function() {
  var inputTitle = $("input").attr("title","class");
  console.log(inputTitle[1])//output:undefined
})();

I'm new to jQuery

Alessio
  • 3,404
  • 19
  • 35
  • 48
Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41

5 Answers5

2

You can't get multiple attributes, you just have to call attr again:

var input = $("input");
var title = input.attr("title");
var cls   = input.attr("class");

Your example sets the value "class" to the title attribute.

Or more similar to your original code:

var inputTitle = [input.attr("title"), input.attr("class")];
inputTitle[1]; // gives you 'maiz'
Dennis
  • 32,200
  • 11
  • 64
  • 79
1

You can try this:

for (var i = 0; i < elem.attributes.length; i++) {
  var attrib = elem.attributes[i];
  if (attrib.specified == true) {
    console.log(attrib.name + " = " + attrib.value);
  }
}
Rusty
  • 1,303
  • 2
  • 14
  • 28
  • `Use of attributes' specified attribute is deprecated. It always returns true.` - according to Firefox – Dennis Apr 15 '13 at 11:32
0

You can get the attributes using the attributes property on the element object:

var el = document.getElementById("someId");
var attributes = el.attributes; // Here they are

In jQuery you can get the Original element with the get() method, like:

var el = $("input").get(0);
var attributes = el.attributes; // Here they are
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
0

Try this:

$('.maiz').click(function(){
    for(var i = 0;i < this.attributes.length;i++){
        console.log(this.attributes[i]);
    }
});

Demo

Eli
  • 14,779
  • 5
  • 59
  • 77
-2

Jquery selector works pretty much like the CSS selector. $('selector') if you want to select all elements if a particular class $('.class') if you want to select class and id $('.class, #id') that's basically it. unless you have a specific question

qualebs
  • 1,291
  • 2
  • 17
  • 34