728x90
SMALL
#jQuery
#attr()
.attr()
.attr() gets the value of an attribute on an element or adds an attribute.
grammar 1
.attr( attributeName )
Add attributes to the selected element. for example
$( 'div' ).attr( 'class' );
will get the value of the class attribute of the div element.
grammar 2
.attr( attributeName, value )
Add attributes to the selected element. for example
$( 'h1' ).attr( 'title', 'Hello' );
adds a title attribute to the h1 element, giving the attribute the value Hello.
example 1
Gets and outputs the value of the class attribute of the h1 element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready( function() {
var hClass = $( 'h1' ).attr( 'class' );
$( 'span' ).text( hClass );
} );
</script>
</head>
<body>
<h1 class="hello">Lorem ipsum dolor.</h1>
<p>h1 class value is : <span></span></p>
</body>
</html>
example 2
Add a placeholder property to the input element with the value Input your address.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<style>
input { font-size: 30px; }
</style>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready( function() {
$( 'input' ).attr( 'placeholder', 'Input your address' );
} );
</script>
</head>
<body>
<input type="text">
</body>
</html>
memo
- If you want to remove an attribute, use .removeAttr().
- Use .css() to get the css attribute value of the selected element or add a style attribute.
- .prop() gets or adds an attribute value in JavaScript's terms.
728x90
LIST