Trying to replace a word inside a div


I have this structure:

<div class="forc">
    <div class="control">
      <div class="field">London, England, UK</div>

And I am trying to remove everything after the las comma (, UK).

I have this script that locates the content of the div, and I am trying to use it to remove the comma, space and “UK”, but it does not work. In fact, it does not replace anything:

document.querySelector('.forc .control .field').replace(", UK" , " ");

Anybody knows why?

Many thanks.

Hi there andresb,

here is one possible solution…

   var txt=document.querySelector('.forc .control .field').firstChild;
       txt.nodeValue=txt.nodeValue.replace(', UK' , ' ');

There may, of course, be better methods of doing this. :mask:


Thanks coolhead, it work.

Maybe there are other ways, as you say, but this one works like a charm to me.


It works, but only for a first instance. If there more elements in the page, the replacement does not work but for the first one.

Perhaps .firstChild;?

Hey @andresb,

querySelector() only returns the first match - you want querySelectorAll(), which returns an array you can loop over.

of course. querySelector() only matches a single (resp. the first) element. for anything else you need (at least) a loop.

technically a list, since you can’t use array functions.

1 Like

Good point, I always forget about that.

In which case you’ll need to do something like this:

var nodes = document.querySelectorAll('.forc .control .field');
[], function(node) {
  var txt = node.firstChild;
  // etc

Yes, this does work, even in Internet Explorer 8.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.