attr and prop

Get and set HTML attributes and DOM properties.

Syntax$(el).attr("name", value); $(el).prop("checked", true);

.attr() reads/writes HTML attributes (like href, src, title). .prop() reads/writes DOM properties (like checked, disabled).

Which one?

  • Use .attr() for regular attributes: $("img").attr("src", "pic.png").
  • Use .prop() for true/false states: $("#box").prop("checked", true).

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A link builder reads the href attribute with .attr('href') to display the destination URL in a tooltip.
  • A toggle switch reads the checked DOM property with .prop('checked') to decide which panel to display.
  • A lazy-loader sets the src attribute on images with .attr('src', url) only when they scroll into view.

More examples

Read and change an attribute

.attr("href") reads the attribute; .attr("href", value) sets it β€” the same method handles both directions.

Example Β· html
<a id="link" href="https://example.com">Visit site</a>
<button id="change">Change link</button>
<p id="current"></p>
<script>
$(function () {
  $("#current").text($("#link").attr("href"));
  $("#change").click(function () {
    $("#link").attr("href", "https://jquery.com").text("Visit jQuery");
    $("#current").text($("#link").attr("href"));
  });
});
</script>

Toggle checkbox with .prop()

.prop() sets DOM properties like checked, disabled, and selected β€” not HTML attributes β€” for reliable form control.

Example Β· html
<input id="agree" type="checkbox" />
<label for="agree">I agree</label>
<button id="checkAll">Check all</button>
<script>
$(function () {
  $("#checkAll").click(function () {
    $("#agree").prop("checked", true);
  });
});
</script>

Set multiple attributes at once

Passing an object to .attr() sets multiple attributes in one call, keeping the code concise.

Example Β· html
<img id="photo" src="placeholder.jpg" alt="placeholder" />
<button id="load">Load real image</button>
<script>
$(function () {
  $("#load").click(function () {
    $("#photo").attr({
      src: "https://picsum.photos/200",
      alt: "Random photo",
      width: 200
    });
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.
attr and prop β€” jQuery | SoundsCode