Using JavaScript to scan dynamically rendered elements? - javascript

I apologize in advance if I've formulated this question poorly; I'm fairly new to web coding.
My goal is to use JavaScript to scan a webpage and determine whether or not a particular string is present. The difficulty here is that the page is dynamically rendered, so the string in question will never appear in the source code.
Would the string appear in the DOM if it is rendered on the page? If I were to scan the DOM would I find it there, and are there any special considerations to take into account if so?
Essentially I am looking for a simple way to scan the text that has been rendered on a page, not the source code. This must be possible somehow because my browser's "find on page" function works on the dynamically rendered page in question. Would there be a way to access the rendered elements on the page through the browser API itself? (I'm using Chrome.)

Try this:
var stringToSearchFor = 'foobar';
var searchThisString = document.body.innerText || document.body.textContent;
var found = (searchThisString.indexOf(stringToSearchFor) >= 0);
This extracts the text from the page, ignoring all markup, then does a simple scan of the resulting string.
In some versions of FireFox this will include the contents of inline script tags.

Related

highlight.js: CSS styling absent after setting innerHTML

I am using highlight.js for syntax highlighting in a webpage.
When I change the content by setting the relevant innerHTML using JavaScript, the content output on the page updates as expected. However the changed content is not highlighted in the browser.
What is the correct way to deal with this situation, generally or with highlight.js using only JavaScript, HTML and CSS?
I found a solution thanks to #Afsar's insightful comment.
The function initHighlighting from highlight.js:
initHighlighting()
Applies highlighting to all <pre><code>...</code></pre> blocks on a page.
... contains an internal check to see whether it has already been run. Since I was attempting to run it more than once, highlighting was not working correctly.
So one possible solution to updating highlighting after updating content via JavaScript with no page reload is:
var element = document.querySelector(".class_that_contains_code_blocks");
var blocks = element.querySelectorAll('pre code');
blocks.forEach(hljs.highlightBlock);

Inserting HTML comments onto page using Javascript

I have a Javascript function that is supposed to insert a string formatted in a certain fashion onto a page for a data analytics tool used by another team. The Javascript executes without error, but whenever I look at the page source of the page, it appears that the comment is not present on the page. Does anyone have any ideas what the issue could be? Has anyone had any experience with writing comments onto the page? I thought maybe jQuery was having any issue with writing HTML comments, but it turns out that using just plan Javascript DOM manipulation functionality doesn't work either.
var test_comment = "<!--This is my comment for data analytics-->";
renderTealeafGrid: function(analyticsString) {
var homePage,
analyticsInfo;
if($('.analyticsInfo').length===0) {
homePage = document.getElementById('homePage');
analyticsInfo = document.createElement('span');
analyticsInfo.setAttribute('class','analyticsInfo');
analyticsInfo.innerHTML = analyticsString;
homePage.appendChild(analyticsInfo);
}
}
renderTealeafGridUsingJQuery: function(analyticsString) {
if($('.analyticsInfo').length===0) {
$('#homePage').after('<span class="analyticsInfo hide">' + analyticsString + '</span>');
}
}
None of the logic that you presented does anything with the test_comment variable.
As others have noted, simply View Source will display the original source code of the page, not any DOM changes after the page has been loaded. You will need to Inspect the source using Firebug or Chrome Dev Tools.
Also, if you want to properly add a comment to the DOM, you would use the document.createComment() method.
// Assuming you are simply viewing source of the page.
Your problem is, jQuery manipulates DOM after it had been built.
And DOM is built based on the source of the page which is what you are seeing through 'view source'.
To view the modified source, either inspect element or use firebug like tool.
You can also get the source through jQuery. Try alerting a .html() of the element you are updating.
If you use the old-fashioned view source tool, you will probably see the original source. You can verify the changes in FF by using the Inspect Element array of tools. They show the current DOM, after updates.

JavaScript: Changing Language Without Page Reload

I am implementing multilingual support into my webpage. I would like to minimize the page blinking caused from page reload, and I came to the idea to change page language without forcing the whole page to reload. To achieve this, the only possible way that comes to my mind is with the use of JavaScript:
I dynamically load appropriate language .js file with appropriate translations
I manually go through every text object on the page and update it by re-sending the appropriate new text value
To provide you with example code, I paste a code that will update just submit buttons. On the language change, I call a function that loads appropriate .js language file dynamically.
var fileRef = LoadJsCssFile("Language/svk.js", "js", UpdateLanguage);
After the language .js file is fully loaded, I call the function that updates every element containing text on the webpage:
function UpdateLanguage()
{
var buttons = document.getElementsByClassName("submit_button");
for (buttonID in buttons)
{
buttons[buttonID].innerHTML = lang.SUBMIT;
}
};
Manually updating every text object in the webpage is complex and error prone. As I am not very experienced with JavaScript yet, I was thinking, if there is a way to simply refresh the all key elements in the webpage with one JavaScript command without casing the webpage blink?
If you have any other idea, how to effectively implement language change without page blink, I am interested to know. :-)
I found a solution on my own:
I prepare several javascript language files containing strings per every keyword
On language selection button, I import appropriate language file for the language I wish to use
I manually update every text on the webpage through javascript.
The above solution is suitable for smaller sites. for large ones, that would be a lot of work, to update every single text string through javascript.

Way to edit style of another webpage within iframe, even superficially?

Is there any way at all to edit the way a page looks within an iframe? I want to change the color of specific links on, say, a google search within an iframe.
Also, why doesn't the code below work in javascript console when google.com is loaded normally?
document.body.getElementsByTagName("a")[0].style.color='red';
You can't modify content from another domain with Javascript even through an iFrame. If you want to attempt something like this you could site scrape get all the html elements and then display them on your own page using a server side language (getting around domain restrictions of JavaScript).
You don't have javascript access from one frame to another one loaded from a different domain.
For the second question, test this :
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++) test[i].style.color="red";
The difference with your code is that I change all "a" elements, not just first one.

Possible to create custom "DOMs" by loading HTML from string in Javascript?

I'm trying to parse HTML in the browser. The browser receives 2 HTML files as strings, eg. HTML1 and HTML2.
I now need to parse these "documents" just as one would parse the current document. This is why I was wondering if it is possible to create custom documents based on these HTML strings (these strings are provided by the server or user).
So that for example the following would be valid:
$(html1Document).$("#someDivID")...
If anything is unclear, please ask me to clarify more.
Thanks.
var $docFragment = $(htmlString);
$docFragment.find("a"); // all anchors in the HMTL string
Note that this ignores any document structure tags (<html>, <head> and <body>), but any contained tags will be available.
With jQuery you can do this:
$(your_document_string).someParsingMethod().another();
You can always append your html to some hidden div (though innerHTML or jQuery .html(..)). It won't be treated exactly as a new document, but still will be able to search its contents.
It has a few side-effects, though. For example, if your html defines any script tags, they'll be loaded. Also, browser may (and probably will) remove html, body and similar tags.
edit
If you specifically need title and similar tags, you may try iframe loading content from your server.

Categories