getAttribute()/setAttribute( )

You can collect the value of an element’s attributes using the getAttribute( ) method. Assuming the same (X)HTML as the example above, you could use getAttribute( ) to collect the value of the anchor’s href attribute and place it in a variable called href:

var href = document.getElementById( 'easy' ).getAttribute( 'href' );

The value returned by getAttribute( ) is the nodeValue of the attribute named as the argument.

Similarly, you can add new attribute values or change existing ones using the setAttribute( ) method. If you want to set the href value of a specific page on url="http://easy-designs.net"/>, you could do so using setAttribute( ):

var link = document.getElementById( 'easy' );
link.setAttribute( 'href', 'http://www.easy-designs.net/index.php' );

You could also add a title to the link using setAttribute( ):

link.setAttribute( 'title', 'The Easy Designs, LLC homepage' );

This brings us to our next topic: creating document structure using the DOM.

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.