//example one: expected use where a div with ID exists
//changeInnerHTMLByIdOrExisting("age", "Age: 35", "Age: 34");
//example two: find expected matching HTML contents of a node, update it and set the id to the expected value
//changeInnerHTMLByIdOrExisting("missingId", "Age: 36", "no ID");
//example three: no matching id or content found: create the entire node
changeInnerHTMLByIdOrExisting("missingNode", "Age: 37", "no Value");
function changeInnerHTMLByIdOrExisting(id, update, existing) {
try {
var newElement = undefined;
document.getElementById(id).innerHTML = update;
} catch (error) {
try {
var elements = document.getElementsByTagName('*');
for (var i = 0, x = elements.length; i < x; i++) {
console.log(elements[i].innerHTML);
if (elements[i].innerHTML === existing) {
alert("Match found");
elements[i].innerHTML = update;
id = elements[i].id;
break;
}
}
if (i === x) {
throw new Error("An existing element was not found.");
changeInnerHTMLByIdOrExisting("age", "Age: 35", "Age: 34");
}
} catch (error2) {
alert(error2.message + "\nCreating new text node.");
newElement = document.createTextNode(update);
document.body.appendChild(newElement);
}
} finally {
if (newElement !== undefined) {
console.log("Returning new text node...");
return newElement;
} else {
console.log("Modified element \"" +
(id || existing) +
"\" with inner HTML \"" +
update + ".");
}
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.