0

I need some expert advice.

The project I'm working on is report generated in HTML. I need to use javascript to
1. Find a number and extract a part of it
2. Increment/Decrement the extracted part
3. Replace the number with new value
4. Replace other elements

Also, the html I'm working with has no tags or ids, so I'm forced to grab the entire content.

Here is what I have so far: http://jsfiddle.net/y6Hy7/3/

var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  var txt = els[i].textContent; //grabbing the text
  var patt = /\d+(?=,[0-9]{3}\sPARTS)/g; //regex pattern only grab the first 2 digits
  var res = patt.exec(txt); //execute regex on text
  if (res !== null) { //see if its not null
    var toNum = parseInt(res,10) +10;
  } //convert to int and add some fixed value
  el.innerHTML = el.innerHTML.replace(patt, toNum); //replace the original
  el.innerHTML = el.innerHTML.replace("text need to be changed and looped", "replaced");
}

It works, but keep increasing the replaced value too many times. How can I fix that?

2
  • "html I'm working with have no tags" - wait, what..? Commented Jul 11, 2014 at 9:24
  • Let me rephrase that, no tags I can grab with getElementsByTagName, it basically <html> <head> <body>, and <p> and some tables, other than that, no ID, or other formatting. Commented Jul 11, 2014 at 9:38

1 Answer 1

1

Find only p tags Not for All

Do like

var els = document.getElementsByTagName("p");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  var txt = els[i].textContent; //grabbing the text
  var patt = /\d+(?=,[0-9]{3}\sPARTS)/g; //regex pattern
  var res = patt.exec(txt); //execute regex on text
    if (res !== null) { //see if its not null
    var toNum = parseInt(res,10) +10; } //convert to int and add 10
 el.innerHTML = el.innerHTML.replace(patt, toNum); //replace the original
 el.innerHTML = el.innerHTML.replace("text need to be changed and looped", "replaced");

  }

if you find all elements using TagName("*"). the els array looks like

[html, head, meta, title, script, link, style, script, body, p, p, p, p, p]

so loop executed 14 times.

if you still want to use this collect all the elements and remove First 9 elements from it.

like

var els = document.getElementsByTagName("*");
els.splice(0,9)
alert(els);

Now els contains only remaining Elements.

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but it sometimes in <BR> tag, or not even in <p>, tho i can actually grab element inside BODY that prevent the script to loop trough itself.
find var els1 = document.getElementsByTagName("br"); now combine els=els+els1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.