Simple javascript

Simple javascript

RobinHood

Member
Local time
01:30
Joined
Jan 6, 2020
Messages
26

I don't know js, but I'm trying to figure out a simple text replacement on content that is loaded from an iframe.

Within the iframe there's a .campaign class

I'm trying to select the contents of each campaign div, find a dash '-' and remove it.

I tried the following and it doesn't seem to work.

JavaScript:
    var x = document.querySelectorAll(".campaign");
    for (i = 0; i< x.length; i++) {
        x[i].innerText.replace("-", "");
    }

When I run it in the console it outputs the updated text properly with the dash removed, but doesn't update it on the page itself.

I'm not sure how to insert the variable contents back into the dom, or alternatively just loop through the live .campaign divs in the dom and do the replacement direct on them.

Can anyone help?

Thanks

 
Last edited:

Gummibeer

Astroneer
Moderator
Local time
02:30
Joined
Oct 5, 2019
Messages
1,150
Pronouns
he/him

You simply miss the assignment back to the innerText.

Code:
    var x = document.querySelectorAll(".campaign");
    for (i = 0; i< x.length; i++) {
        x[i].innerText = x[i].innerText.replace("-", "");
    }

But you also can use forEach instead of the for loop.

Code:
Array.from(document.querySelectorAll(".campaign"))
    .forEach(function (el) {
        el.innerText = el.innerText.replace('-', '');
    });

 

RobinHood

Member
Local time
01:30
Joined
Jan 6, 2020
Messages
26

Ah, brilliant, cheers @Gummibeer!

That works, but it also removes the link in the div.

Original div looks like this:

HTML:
<div class="campaign">09/06/2020 -
<a href="http://us12.campaign-archive.com/....." title="Newsletter - JUNE " target="_blank">Newsletter - JUNE</a>
</div>

And the replaced div looks like this:

HTML:
<div class="campaign">09/06/2020
<br>
Newsletter - JUNE</div>

So I read up about textContent innerText and innerHTML

Turns out innerHTML is what I wanted!

Final working code as follows:

JavaScript:
    var x = document.querySelectorAll(".campaign");
    for (i = 0; i< x.length; i++) {
        x[i].innerHTML = x[i].innerHTML.replace("2020 -", "2020");
    }

or

JavaScript:
    Array.from(document.querySelectorAll(".campaign"))
    .forEach(function (el) {
        el.innerHTML = el.innerHTML.replace('2020 -', '2020');
    });

All this just to remove a few dashes from a Mailchimp embed form that has been reshuffled around to bit to change to order the content is displayed 🙈

 
Last edited:
Top