If I have html like this:
This is some text
First span text
Just like the question, I was trying to extract text in order to do some regex substitution of the text but was getting problems where my inner elements (ie: The following code seems to work well and solved all my problems. It uses some of the answers provided here but in particular, will only substitute the text when the element is of What the above does is loop through all the elements of the given The This short code excerpt will help anyone trying to do what the question was asking ... and a bit more.,
, etc.) were getting also removed.
nodeType === 3
.$(el).contents().each(function() {
console.log(" > Content: %s [%s]", this, (this.nodeType === 3));
if (this.nodeType === 3) {
var text = this.textContent;
console.log(" > Old : '%s'", text);
regex = new RegExp("\\[\\[" + rule + "\\.val\\]\\]", "g");
text = text.replace(regex, value);
regex = new RegExp("\\[\\[" + rule + "\\.act\\]\\]", "g");
text = text.replace(regex, actual);
console.log(" > New : '%s'", text);
this.textContent = text;
}
});
el
(which was simply obtained with $("div.my-class[name='some-name']");
. For each inner element, it basically ignores them. For each portion of text (as determined by if (this.nodeType === 3)
) it will apply the regex substitution only to those elements.this.textContent = text
portion simply replaces the substituted text, which in my case, I was looking for tokens like [[min.val]]
, [[max.val]]
, etc.