12/17/2017 - 11:40 PM

JavaScript and the DOM part 2: Inline CSS

/*Set INLINE CSS to an element*/
document.querySelector(".cta a").style.color = "green";
document.querySelector('.cat a').style.cssText = "padding: 1em; color: white; background-color: blue;"; // use to change entire inline style for that element.

.hasAttribute("style"); //does the element have a current inline style applied?
.getAttribute("style"); //get the current inline styles
.setAttribut("style", "color: red"); //add inline css
.removeAttribute("style"); //remove all inline styles for that element.

document.querySelector('.cta a').setAttribute('style', "padding: 2em");

// Inline styles override whatever the style sheet is doing, which can be problematic. If you're using JavaScript to apply basic style changes, it is usually better to create a custom CSS rule targeting class selectors, and adding or removing these classes from the element instead. It's cleaner, easier to manage, and preserves the separation between content, presentation and interactivity, we talked about in the very beginning of the course.