I'm using a custom Primefaces/JSF based framework for my page. Unfortunately, by default it sets many unwanted title attributes, so now my last resort is a short JavaScript that's embedded on every page that clears the title attribute of every element (that has one set, at least).
Is there a smarter method than simply iterating through all elements and setting the attribute to null for each?
You can target only the elements that have target attributes by using an attribute presence selector ([title]):
for (const element of document.querySelectorAll("[title]")) {
element.removeAttribute("title");
}
That does involve creating an interim NodeList, which you could avoid with a recursive tree traversal. Recursive tree traversal sounds complicated, but it isn't particularly:
function removeTitle(element) {
element.removeAttribute("title");
for (const child of element.children) {
removeTitle(child);
}
}
removeTitle(document.documentElement);
I was tempted to have
if (element.title) { // `title` is a reflected attribute
element.removeAttribute("title");
}
instead of just
element.removeAttribute("title");
...but even though it doesn't look like it, element.title is a function call (title is an accessor property), so it probably doesn't make sense to do the check. (I'm also probably overthinking it.)