Skip to content

Instantly share code, notes, and snippets.

@paulnguyen-mn
Created February 21, 2020 09:34
Show Gist options
  • Save paulnguyen-mn/3f7ef03a31c5e3fad19ac1a5cf7dd708 to your computer and use it in GitHub Desktop.
Save paulnguyen-mn/3f7ef03a31c5e3fad19ac1a5cf7dd708 to your computer and use it in GitHub Desktop.
Get/Set text, value or background image url by elementId
const setTextByElementId = (elementId, text) => {
const element = document.getElementById(elementId);
if (element) {
element.innerText = text;
}
};
const setValueByElementId = (elementId, value) => {
const element = document.getElementById(elementId);
if (element) {
element.value = value;
}
};
const getValueByElementId = (elementId) => {
const element = document.getElementById(elementId);
return element ? element.value : null;
};
const setBackgroundImageByElementId = (elementId, imageUrl) => {
const element = document.getElementById(elementId);
if (element) {
element.style.backgroundImage = `url(${imageUrl || AppConstants.DEFAULT_IMAGE_URL})`;
}
}
const getBackgroundImageByElementId = (elementId) => {
const element = document.getElementById(elementId);
if (element) {
const url = element.style.backgroundImage;
const firstDoubleQuotePosition = url.indexOf("\"");
const lastDoubleQuotePosition = url.lastIndexOf("\"");
return url.substring(firstDoubleQuotePosition + 1, lastDoubleQuotePosition);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment