jquery get attribute code example

Example 1: get attribute value jquery href

var href = $(this).attr('href');

Example 2: jquery get data attribute value

/* html */
<a data-id="123">link</a>

/* js */
$(this).attr("data-id") // returns string "123"

$(this).data("id") // returns number 123 (jQuery >= 1.4.3 only)

Example 3: jquery add attribute

$('#someid').attr('name', 'value');

Example 4: get attribute value jquery

var some_var = $( some_jquery_selector ).attr( 'some_attribute_name' );

Example 5: jquery set att

$input.attr("attributeName", "attributeValue");

Example 6: jQuery - Get Content and Attributes

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert("Text: " + $("#test").text());
  });
  $("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
  });
});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>

<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>

</body>
</html>

Tags:

Java Example