.attr()

.attr() Method

  • Method to either get the value of an element’s attribute or set one or more attributes for the selected element

Example of Getting (Reading) attributes from elements

  • To Get (Read) text of an element use .attr(attrName) with name of the attribute you want to receive a value for
$(() => {
  $("#getIdName").click(() => {
    // read class name of .box
    const idName = $(".box").attr("id")
    alert(idName)
  })

  $("#getUrl").click(() => {
    // read href of a tag
    const url = $("a").attr("href")
    alert(url)
  })
})

JS Bin on jsbin.com


Example of Setting (writing) attributes to elements

  • To Set (Write) text of an element use .attr(attrName, attrValue) with the new attribute name and value inside the parentheses
$(() => {
  $("#setClassName").click(() => {
    // set class name of #box to .green
    $("#box").attr("class", "green")
  })
})

JS Bin on jsbin.com