What's an attribute again? What are some examples of attributes? →
<element attributeName="attributeValue">
type
in input elements
, the src
in an img
tagMost 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";;
}
HTML actually lets you create your own attributes… so you can add any attribute you'd like to elements. →
<p data-highlight>
The following methods can be called on elements in order to read or set attributes:
element.getAttribute(name)
- gives back value of attribute with specified name; if it doesn't exist, depending on implementation, you'll get back null or empty stringelement.setAttribute(name, value)
- changes attribute with specified name to specified value; if attribute doesn't exist, create it with that valueelement.hasAttribute(name)
- returns true if attribute exists in element, false otherwiseYou 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')
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 expressionUsing 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, '!!!!!');
}
}