Back to HTML Elements, Attributes

CSCI-UA.0480-008

Element Attributes

What's an attribute again? What are some examples of attributes?

  • it's additional information about the element
  • it's written as a name/value pair within an opening tag: <element attributeName="attributeValue">
  • some examples include the type in input elements, the src in an img tag

Changing Attributes

Most attributes can be accessed as properties on that particular element's object. The property name is usually just the camel-case name of the attribute.

Try writing a tiny script that takes all of the images on a page and changes the src of those images to the look of disapproval


const images = document.getElementsByTagName('img');

for (let i=0; i < images.length; i++) {
	images[i].src = "http://foureyes.github.io/csci-ua.0480-fall2017-007/resources/img/disapproval.png";;
}

Any Attribute!

HTML actually lets you create your own attributes… so you can add any attribute you'd like to elements.

  • generally, custom attributes are prefixed with data (you'll see this in many frameworks, such as Angular.js)
  • data-* attributes allow you to store extra information on standard, semantic HTML elements
  • (see the using data attributes article on mdn)
  • for example: <p data-highlight>

Getting and Setting Attributes

The following methods can be called on elements in order to read or set attributes:

You could use these methods on both standard element attributes, such as href, value, etc. … but they're also useful for custom attributes

Let's try these out on our sample page


// change an image's src (similar to just using the attribute)
document.getElementsByTagName('img')[0].setAttribute('src', 'http://foureyes.github.io/csci-ua.0480-fall2017-007/resources/img/disapproval.png')

// check for a class attribute... and try to read it
document.getElementById('content').hasAttribute('class')
document.getElementById('content').getAttribute('class')

// set it
document.getElementById('content').setAttribute('class', 'highlight');

// check again, and read it
document.getElementById('content').hasAttribute('class')
document.getElementById('content').getAttribute('class')

Data-* as JavaScript Hooks

We can use data-* attributes as hooks for our JavaScript.

Create a script that substitues all of the periods with 5 exclamation points in the sample page. Only do this for paragraph elements that have a data-shout attribute.

You can use the string's replace method and a regular expression to do this: replace(/\./g, '!!!!!')

  • /'s mean regular expression
  • \. is match period
  • the g after the regex delimiters mean find all matches instead of just the first (global)

A Potential Solution

Using a data-* attribute…


const paragraphs = document.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
	if (paragraphs[i].hasAttribute('data-shout')) {
		paragraphs[i].textContent = paragraphs[i].textContent.replace(/\./g, '!!!!!');
	}
}