Elements attr() - KirkGarcia182/domExtend GitHub Wiki

attr()

Description

Sets and Gets element attributes

Syntax

// get the attribute value of the element
element.attr(attributeName);

// set a single attribute to an element
element.attr(attributeName, attributeValue);

// set multiple attributes to an element
element.attr({
   attributeName1: attributeValue1,
   attributeName2: attributeValue2,
   attributeName3: attributeValue3,
});

Parameters

attributeName - can be a String containing the attribute name you want to get or set, or an Object Literal containing the attributeName and attributeValue pairs.

attributeValue (Optional) - a String containing the attribute value you want to set if you have passed a String on the attributeName parameter.

Return Value

If you're getting the element's attribute, then it will return the value of the element's attribute.

If you're setting the element's attribute then it will return element you just manipulated so you can chain these methods.

Example

<!DOCTYPE html>
<html>
<head>
	<title>domExt Examples</title>
</head>
<body>
	<div id="app">
		<div class="menus">
			<ul id='menuList'>
				<li><a>Menu 1</a></li>
				<li><a>Menu 2</a></li>
				<li><a>Menu 3</a></li>
			</ul>
		</div>
	</div>
	<script type="text/javascript" src="domExt.js"></script>
	<script type="text/javascript">
		window.$ = document;

		let app = $.byId('app');
		// set a single attribute to the element
		app.attr('title','domExt is awesome!');
		console.log(app); 
		/* Result 
			<div id='app' title='domExt is awesome!'>
		*/

		// set multiple attributes to the element
		app.attr({
			title: 'domExt is the best!',
			style: 'color: lime',
			class: 'class1'
		});

		console.log(app); 
		/* Result 
			<div id='app' title='domExt is the best!' style='color: lime' class='class1'>
		*/

		// get element attribute
		let title = app.attr('title');
		console.log(title);
		/* Result 
			domExt is the best!
		*/
	</script>
</body>
</html>
⚠️ **GitHub.com Fallback** ⚠️