-1

This a slightly open ended question but i am hoping someone can help. Here is what I am trying to do.

I am writing a browser extension that parses all the HTML of the page, calls an API, waits for a response and then replaces all the text on the page with the text from the API response without changing the format of the page.

I have tried several different approaches to parsing the HTML of the page -

  1. Grab document.body.getElementsByTagName("*") and then try to process some of those elements at a time. The disadvantage is that I end up with a list of all the elements of the page which includes the parents and the children, so I end up calling the API on the same element twice

  2. Grab document.body.childnodes and then work my way down each child node. This isn't working because some child nodes tend to be too big and end up overflowing the API.

So my open ended question is this - If you have to traverse the DOM of any page on the web and replace all the text with another chunk of text, what is the best approach to take?

tsurti
  • 17
  • 4
  • 2
    Give an example. As a simple text change does not require complex thingies like DOM traversals. – Itay Moav -Malimovka Feb 27 '15 at 02:35
  • The answer depends a great deal on details you have omitted. What is the format/layout of the page? What is the structure of the API result? **Give concrete examples!** – Brock Adams Feb 27 '15 at 03:13
  • You probably don't want to replace *all* text on *every* website with something else. that wouldn't be useful, or would it? – Tomalak Feb 27 '15 at 03:13

2 Answers2

0

You'll probably have to write your own function using javascript to go in and grab each elements text you're interested in.

Have you worked with jquery before? It's built off of javascript. Would make going in and grabbing the "text" you're interested in a little easier.

".text()" might be what you're looking for if you go the jquery route:

http://api.jquery.com/text/

var innerTxt = $('#elementWithText').text();

$('span').text(innerTxt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="elementWithText">Hello, how are you</p>

<br>
<p>The text in the paragraph above is: </p>
    
<span></span>
John23
  • 189
  • 2
  • 4
  • 14
  • `$.text()` returns the text of all nested elements too. Not sure if this is an issue for this case, but it's something to consider – jasonscript Feb 27 '15 at 03:42
0

you can use Reactjs for dom update and faster performance.

TechnoCrat
  • 710
  • 10
  • 20