Inserting HTML comments onto page using Javascript - 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.

Related

document.querySelector() returns null when DOM elements are already visible

I am trying to build an automated Puppeteer script to download my monthly bank transactions from my bank website.
However, I am encountering a strange error (see attached Imgur for pictures of this behavior)
https://imgur.com/a/rSwCAxj
Problem: querySelector returns null on DOM element that is clearly visible:
Screenshot: https://imgur.com/d540E6p
(1) Input box for username is clearly visible on site (https://internet.ocbc.com/internet-banking/),
(2) However, when I run document.querySelector('#access-code'), console returns null.
I'm wondering why this behavior is so, and what are the circumstances that a browser would return null on a querySelector(#id) query when the DOM node is clearly visible.
# EDIT: Weird workaround that works:
I was continuing to play around with the browser, and used DevTools to inspect the DOM element and use it to Copy the JS Path.
Weirdly, after using Chrome Devtools to copy the JS Path, document.querySelector('#access-code') returned the correct element.
Screenshot of it returning the correct element: https://imgur.com/a/rSwCAxj
In both cases, the exact same search string is used for document.querySelector.
I believe that you cannot get proper value using document.querySelector('#access-code') because a website use frameset.
In the website there is frame with src to load content
<frame src="/internet-banking/Login/Login">
DOMContentLoading is executed when main document is loaded and not wait for frame content to be loaded.
First of all you need to have listener for load event.
window.addEventListener("load",function() {
...
});
And later on you cannot simply use document.querySelector('#access-code')
because input yuo want to get is inside frame. You will need to find a way to access frame content and than inside of it use simple querySelector.
So something like:
window.addEventListener("load",function() {
console.log(window.frames[0].document.querySelector('#access-code'));
});
BTW please see in: view-source:https://internet.ocbc.com/internet-banking/ looks like website is mostly rendered client-side.

How is blockchain hiding its HTML source?

When you navigate to: blockchain.info
You will notice that if you click view-source on the page, it will show HTML context different than that when you inspect-element. My question is, how are they doing this?
I understand they are using .pug templates from AngularJS framework. But how does my browser know where to read them from if they are not loaded from the client-(browser)-side?
Also, if I was to insert jQuery onto the page, would the jQuery know when the events are triggered on('click', 'submit', 'whatever') etc ...?
When you click View Source, you see what the server sends back. Many pages do not send back a full HTML page, instead some skeleton HTML and add the rest of the functionality via JavaScript
When you Inspect Element, you're viewing the browser's representation of the DOM, which includes any manipulations done via JavaScript. For a visual explanation, see this article on css-tricks: https://css-tricks.com/dom/
Any framework that is rendering HTML client-side (React, Angular, Vue) will do that. The actual source code could literally just be some basic html boilerplate and a div that then gets loaded with an application through something like Javascript. Thus, when you view the source of the page, you're seeing this basic templating. But when inspecting an element, Chrome Dev tools (and others) are inspecting the element that is being rendered client side. Your browser has placed those elements on the DOM, they didn't exist in the source code till the code executed. Hope that helps clear things up.

How do I see what javascript modifies a particular bit of HTML?

When I load a page, there is a style attribute that has been added to the <body> tag that is not there in my templates. How do I discover what javascript has modified it?
Just to be clear, the body tag is now:
<body class="home page" style="margin-top: -43px;">
So the style is not coming from a style sheet. While the template does not include the "style=" bit at all. So I'm pretty sure that some running javascript is modifying the body tag.
I have both Firefox/Firebug and Chrome Inspector available to me. I have tried right clicking on the body tag in "HTML"/"Elements" view and choosing "break on attributes modification" but the change has happened by the time I can do that, and the break point does not survive a page reload.
I'm using Django and jQuery in case that alters the answer.
I currently use an extension of Firebug called FireDiff you can file its homepage here: http://www.incaseofstairs.com/firediff/
You could use mutation observers.
Try adding this code as the first thing that gets executed on page load:
var target = document.querySelector('body'),
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
debugger;
});
});
  
observer.observe(target, { attributes: true });
As a side note, it'd be great if that particular kind of breakpoints survived page reload.
There is the possibility it is added server side too. If you search your source files for the stylesheet name it should appear in either a JavaScript or a Python file. i.e. grep for "mystylefile.css"
You could disable JavaScript and see if it is still added if you want to narrow it down.
Update
Finding what added the margin-top to the element will be harder! You could search your JavaScript files for "margin-top" and see how many results you get back - or add the JavaScript files one by one until one causes it to be added.

I can't get the toggle control with document.GetElementByID() in the windows8 setting charm

I'm very new to javascript, so this is confusing me. All of the settings charm tutorials only show how to put the controls into the settings charm, but none of them say how to find the information gotten in them.
I tried to do one of these (like I do in the main program):
var muteToggle = document.GetElementById("Mute");
where "Mute" is the id in the separate html file.
muteToggle just ends up being null all of the time. I tried putting it after
WinJS.UI.ProcessAll().then(function completed() {...
but that didn't work either. Everything else is the same as in this page: http://msdn.microsoft.com/en-us/library/windows/apps/hh780611.aspx
Make sure you're doing it in the ready function of the js file that is referenced from your settings HTML. Try opening the JavaScript console or QuickWatch while broken at that line and also look at the DOM Explorer to see if you can find your toggle control. You should be able to access it though. Also, try element.getElementById instead of document.getElementById. Either should work actually, but as long as you're troubleshooting. Good luck.
Your problem is that you are trying to get a reference to the HTML element from the code running during the app activation. Although that piece of code may define the HTML to be loaded for a settings pane, it does Not actually load the HTML into the DOM. You just simply can't get the instance from that location.
What you need to do is have the settings flyout have its own js file that implements IPageControlMembers. In particular, you need to implement the ready method. This method is called once all the HTML and controls are loaded for the page, including your toggle. The link has an example of how to do this.
Also see:
WinJS.UI.Pages.define
Using single page navigation

Update window hash (at url)

So I have this js code for an image gallery:
(this.settings.update_window_hash) {
var thumb_link = this.images[this.current_index].thumb_link;
if (thumb_link.attr("id")) {
window.location.hash = "#image-"+ thumb_link.attr("id"); //#url
} else {
window.location.hash = "#image-"+ this.current_index;
};
};
So as you've probably assumed this appends $image-(int) to the url. So if I have a
gallery with multiple images if the thir image is selected the url will look like this:
mysite.com/gallery.html#image-3
All good. But I dont really like this to be appended to the end of the url. So is there
any problem if I remove this part of the script entirely? So regardless the number of
image currently selected the url will look like this:
mysite.com/gallery.html
I've tested it and it works okay. But I'm not very experienced with javascript and I want
to make sure I'm not making a mistake. So
IS IT OKAY IF I REMOVE THIS SCRIPT ENTIRELY? WILL IT CAUSE ANY PROBLEMS?
HUGE THANKS.
Hashes at the end of the URL are optional and not required so YES, you can remove that script if you want (I'm not sure what problem you're trying to solve by removing it). In general, you get more useful answers if you tell us what problem you're trying to solve rather than what solution you're trying to use.
Hashes are used when you want the URL of the page to direct the viewer to some subcontent on that page. If you remove them, your page will still work just fine, but the URL of the page will not reflect which image is displaying. So, if the viewer saves that URL and comes back to it or links to it or anything that keeps a reference to the URL, it will go to the generic version of the page, not the onethat shows a specific image. Whether that is OK is totally up to you and how your page works.
Just use:
location.replace(location.href + "#myhash");
The location.replace method overwrites the current step in browser history. For an example of this in action see http://prettydiff.com/slideshow/
The stuff after the octothorpe normally represents a "name" or "id" from the web page. You can have an anchor tag (<a name='thevalue'>) and the browser will interpret the text after the octothorpe (http://example.com#thevalue) by scrolling to the associated section on the page.
Unless the page has special JavaScript to behave differently. In your case, it depends upon the full functionality of the web page you're writing. If you have smoke tests/unit test/use case tests/other QE tests, you should execute those to ensure that your changes don't break anything.
See http://www.w3schools.com/html/html_links.asp for more description of the standard usage.

Categories