/    Sign up×
Community /Pin to ProfileBookmark

Replace text in a div

I know how to replace text inside a given div:
document.getElementById(“containerID”).innerHMTL = “some new text”;

But I want to change text depending on text that is in an array.

So I have an array:

my_array =
{
‘Good’ : ‘Bad’,
‘Happy’ : ‘Sad’,
}

How can I change the text in a div with the key of the array? So if my div contains the word good I want to change it to bad.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@NedalsDec 18.2008 — document.getElementById("containerID").innerHMTL = my_array['Good'];
Copy linkTweet thisAlerts:
@toicontienDec 18.2008 — Something like this should do it:
[CODE]var key = "";
var el = document.getElementById("containerID");

for (key in my_array) {
if (el.innerHTML == key) {
el.innerHTML = my_array[key];
}
}

el = null;[/CODE]


Check out the for-in loop, which allows you to iterate over the properties of an object. It's also good to note that JavaScript does not support associative arrays, as your "my_array" variable name alludes to. Instead, JavaScript supports iterable objects.
×

Success!

Help @happyharry spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...