Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2411

jquery Getting multiple attributes

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

Upvotes: 3

Views: 5433

Answers (5)

Dennis
Dennis

Reputation: 32598

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'

Upvotes: 2

qualebs
qualebs

Reputation: 1381

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

Upvotes: -2

Rusty
Rusty

Reputation: 1303

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);
  }
}

Upvotes: 1

Eli
Eli

Reputation: 14827

Try this:

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

Demo

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

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

Upvotes: 0

Related Questions