andresb
November 16, 2016, 4:38pm
1
Hi.
I have this structure:
<div class="forc">
<div class="control">
<div class="field">London, England, UK</div>
</div>
</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.
coothead
andresb
November 16, 2016, 6:10pm
3
Thanks coolhead, it work.
Maybe there are other ways, as you say, but this one works like a charm to me.
andresb
November 17, 2016, 12:17pm
4
Greetings.
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');
[].forEach.call(nodes, function(node) {
var txt = node.firstChild;
// etc
});
andresb
November 17, 2016, 1:23pm
9
Yes, this does work, even in Internet Explorer 8.
Thanks.
system
Closed
February 16, 2017, 8:24pm
10
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.