by smitop · 5y ago · 0 comments
// JavaScript one-liner to make the text of element with ID athing uppercase
const makerUpper = function(id) {
document.getElementById(id).innerHTML = document.getElementById(id).innerHTML.toUpperCase();
};
vs // JavaScript one-liner to make the text of element with ID athing uppercase while following all security best practices
const makerUppercase = function(id) {
const element = document.getElementById(id);
element.textContent = element.textContent.toUpperCase();
};I guess part of it is that a one-liner is impossible. Here's what I would write given the prompt
const makeUppercase = (id) => {
const element = document.getElementById(id);
if (element == null) return;
const makeChildNodeUpper = (node) => {
if (node.nodeType === Node.TEXT_NODE) {
node.nodeValue = node.nodeValue.toUpperCase();
} else {
node.childNodes.forEach(makeChildNodeUpper);
}
}
makeChildNodeUpper(element);
}Well, that's one of the central lessons of ML - garbage in, garbage out. There is a lot of garbage code out there and no easy a priori way to distinguish garbage code from good code.
document.getElementById(id).style.textTransform = 'uppercase';