简体   繁体   中英

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 ?

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

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> 

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM