15. Get/Set element attributes

 282 total views,  1 views today

Let’s write the code to get and set attribute on our DOM element. For this we can use a single function attr.

Here we pass in the attribute name and value to the method.

If the value is not passed, we treat it as the get/read method and returns the attribute value with the name.

If the value is passed as a parameter to this method, then we loop through each selection and set the new value as the attribute using the built it setAttribute method.

  // get/set attribute
  Q.fn.attr = function(name, value) {
    if (!this[0]) return;
    if (!value) {
      return this[0].getAttribute(name);
    return this.each(function (e) {
      e.setAttribute(name, value);

Example => Step 15 -> Get/Set attributes

Let’s do a quick test of our code.

Q(() => {
  test("Get Attributes", function() {
    let attr = Q("li.task").attr("name");
    assert(true, attr);
  test("Set Attributes", function() {
    let $li = Q("li.task");
    $li.attr("status", "progress");
    assert(true, $li.html());