A couple of issues:
You have the same id value on more than one element.
DOM elements don't have a length property; you may have wanted .nodeValue.length or .innerHTML.length or .innerText.length or .textValue.length. (To figure out which one, refer to MDN to find out what they each are.)
var title = document.getElementById("event-title");
var length = title.innerHTML.length;
if(length >= 14){
title.setAttribute('style','font-size:8px !important;');
}
else {
title.setAttribute('style','font-size:16px !important;');
}
<h2 id="event-title">Example Title Goes Here</h2>
If you're trying to do this with more than one element, you'll want to use something else to identify them (perhaps a class) and you'll need to use a different lookup (perhaps document.querySelectorAll). Then you can loop through them to do the above:
var titles = document.querySelectorAll(".event-title");
titles.forEach(function(title) {
var length = title.innerHTML.length;
if (length >= 14){
title.setAttribute('style','font-size:8px !important;');
}
else {
title.setAttribute('style','font-size:16px !important;');
}
});
<h2 class="event-title">Example Title Goes Here</h2>
<h2 class="event-title">Short</h2>
(The NodeList returned by querySelectorAll doesn't have forEach on obsolete browsers like IE8-IE11, but you can readily polyfill it:
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
Object.defineProperty(NodeList.prototype, "forEach", {
value: Array.prototype.forEach,
configurable: true
});
}
Example. On IE8 or in IE9+ in [in]compatibility mode, you'll also need to polyfill Array.prototype.forEach. See MDN for how. Or use a for loop.)
Side note: If you're using !important markers in inline styles, it's probably worth stepping back and figuring out why you have things fighting with each other so much, since an inline style wins over a CSS style (regardless of specificity) unless the CSS style has !important on it. So you have dualling !importants, which suggests some refactoring is in order...
Side note 2: Replacing the entire style attribute works, but if you want a more fine-grained approach, assign to properties on the element's style object: title.style.fontSize = "8px";
id(unique identifiers) as many times as you can?idon multiple HTML elements in the same document. That is invalid HTML, and will may produce undefined behavior in JavaScript operating on thoseids. Useclasswhen you have to select multiple elements.