Rk R Bairi
Rk R Bairi

Reputation: 1359

jquery equivalent to find value of certain attribute on an html element

  <div custom-attribute="somevalue"></div>
  var x = document.getElementsByTagName("DIV")[0].getAttribute("custom-attribute");
  console.log(x); //somevalue

Right now i know its for 0th div but it can be on any random div.

Is there a Jquery equivalent of the above to achieve getting the value of an elements attribute ?

Upvotes: 0

Views: 589

Answers (4)

Barmar
Barmar

Reputation: 780974

The equivalent of document.getElementByTagName("name") is $("name").

The equivalent of indexing the result with [i] is .eq(i).

The equivalent of .getAttribute("attr") is `.attr("attr").

So the whole thing is:

var x = $("div").eq(0).attr("custom-attribute");

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

JQuery selectors take the exact same syntax as CSS selectors, so use the attribute selector to locate the element and then the .attr() method to extract the attribute value.

var x = $("div[custom-attribute]");
console.log(x.attr("custom-attribute")); //somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div custom-attribute="somevalue"></div>

But, know that custom attributes are invalid HTML unless they take the form of data-customName, in which case, you'd still select the element the same way, but you'd access the data-* attribute using JQuery's .data() method, like this:

var x = $("div[data-custom-attribute]");
console.log(x.data("customAttribute")); //somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-custom-attribute="somevalue"></div>

And, just for reference purposes, your original vanilla JavaScript code really should have been very similar in the first place because .getElementsByTagName() is going to scan the entire document, which you don't want to do when you are only looking for one element. Additionally, it returns a "live" node list that hinders performance.

var x = document.querySelector("div[data-custom-attribute]");
console.log(x.dataset.customAttribute); //somevalue
<div data-custom-attribute="somevalue"></div>

Upvotes: 1

Ele
Ele

Reputation: 33726

Use the .attr() function.

var x = $("div").attr("custom-attribute");
console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div custom-attribute="somevalue"></div>

Resource

Upvotes: 3

CRice
CRice

Reputation: 32176

JQuery has a .attr method which will do what you want:

// Old way:
var x = document.getElementsByTagName("DIV")[0].getAttribute("custom-attribute");
console.log(x); //somevalue

// JQuery way:
var y = $("div").attr("custom-attribute");
console.log(y) // somevalue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div custom-attribute="somevalue"></div>

Upvotes: 2

Related Questions