How to track which Javascript manipulates with a given HTML element? - javascript

I'm trying to understand how a template works. If I'd open one in a browser I will see some elements. But If I'd explore the HTML code - the containers with elements appeared in the browser is just empty. This is simple: that means that those containers manipulated by some JS code. However I tried to find the container ID in all JS files mentioned by the main HTML document and not succeeded.
I think that I need some tool which will allowed me to track the JS which changes the given element (place a break-point or make a HTML change log...).
Is there any useful way to do this thing?

It sounds to me all you want is the Web developer's console. In Chrome it is available through Ctrl+Alt+J (Cmd instead of Ctrl for Macs) and in Firefox with Ctrl/Cmd+Alt+K. Alternatively, simply find those buttons in the browser's options/settings menu.
Once you have the console open, click the mouse-pointer icon to manually select any element on the screen you want for inspection. You can also look at the HTML DOM tree directly on the HTML tab. It's all very visual, interactive and intuitive, so just explore a bit.

you can use console.log('// your breakpoint text'); in javascript. It will be shown in your browser console. That way you can track javascript execution flow.
But the tracking process depends on you. You have to do it manually. Try placing the console.log() from the beginning.
In chrome's dev tool. Find the tab with title "Console". Your breakpoint text will be shown there.

You can use debugger; where you add html to dom and by using the console you can check in realtime how your javascript is running.
Another way is to have alerts which you keep on shifting to the next code execution until it goes away from the DOM

Related

Find out what file/line in JS is changing the text of an element

I'm working on a pretty large (a lot of files) and poorly organized web project for a client. Somewhere in the mess of things there is some JavaScript that is truncating H3 tags and adding ellipsis to them. I would like to find that line of script and remove it. I just need to find out where it is...
Manually searching through all of the files on the site could take forever (since, due to the poor code of the site, the JS that produces the dom manipulation could exist in a PHP file somewhere, or in a JS file, or...who knows).
I know that with Chrome, for example, you can do DOM manipulation breakpoints. The problem is that from what I can tell the Subtree modifications and Attributes modifications breakpoints don't actually break on simple text modifications.
Are there any options in any browser to listen on the DOM element and see where the script is that is modifying it?
Add debugger calls in each one of your js files to force the execution to pause on each file. If the h3 changes after jumping a specific stop point, chances are the guilty script is in that page (or the function is being called on that page).
To check whether the change happens on the server or client side you should first check the network reponses. If the text is truncated inside the server response, then the change already happens on the server side. If not, it happens on the client side. When it happens on the client side, it may be done either through JavaScript or through CSS.
Firebug
Check server response
Switch to the Net panel, focus the search field, ensure that the Response Bodies option is checked, then enter the heading (untruncated). If it is found, then the change happens on the client side.
Check CSS
In case the change happens on the client side, it may be part of some CSS.
E.g. there is a CSS property called text-overflow, which allows to add an ellipsis to the text.
To check that inspect the related element and search within the Styles or Computed side panel whether the text-overflow property is set for the element.
The ellipsis may also be achieved via some trick setting the content property to an ellipsis.
If you cannot find any CSS like that, the change probably happens via JavaScript.
Check JavaScript
you can stop the script execution at the line that changes it by right-clicking the element you want to inspect within the HTML panel and choose Break On Child Addition or Removal.
Once the text is changed, the script execution stops at the related line.
Example
<p>foo</p>
<button onclick="changeText()">Change text</button>
<script>
function changeText() {
var p = document.querySelector("p");
p.textContent = "bar";
}
</script>
Set the Break On Child Addition or Removal for the <p>foo</p> element to try it out.
Note: Unfortunately Firebug doesn't always jump to the right script or position, but at least it does stop when the change happens within JavaScript.
Chrome DevTools
Check server response
Switch to the Network panel and search for the untruncated heading in the response bodies of the network requests. (As far as I know, there is no way to search automatically within the response bodies.) If it is found, then the change happens on the client side.
Check CSS
As described above, the change may also be part of CSS.
To check that inspect the related element and search within the Styles or Computed side panel whether the text-overflow or the content property is set for the element.
If you cannot find any CSS like that, the change probably happens via JavaScript.
Check JavaScript
Within the Chrome DevTools it works similar like in Firebug. So, in case the change happens on the client side, right-click the element within the Elements panel and choose Break on > Subtree modifications from the context menu.
Once the text is changed, the script execution stops at the related line.

Javascript DOM-event origin and dependencies

Imagine that there's a button on one web page (not mine) and when it's clicked it performs some
Javascript. I want to have a button on my web page that performs exactly the same. So I need to
attach all necessary js files (but first I have to find them) to my html page and sometimes add some js to my html page.
What I usually do in this case? I inspect this button html element to see if there's onclick attribute for this button. If it is, I see the function called when button is clicked and then I try to search for this function in current html page and all js files attached to page. Also I need to find all dependencies (like jQuery, fancybox etc.).
If the button doesn't have onclick attribute I have to look for direct getElementById or jQuery selector pointing to this button with rest of code there. Sometimes there's no such a selector and I have to find a nested selector - really hard and annoying thing.
Is there any better, automated way for doing things above. Ideally after selecting the element in DOM (button in this case) and pressing some magic button I will be able to see all js files involved in processing this click and also js code in html page.
It's going to involve digging no matter what you do. But Chrome's Dev Tools can help with the attached event handlers, to an extent. When you right-click an element and inspect it, on the right-hand side there's a panel showing various tabs: [Styles] [Computed] [Event Listeners] [DOM Breakpoints] [Properties]. The [Event Listeners] one shows the listeners directly attached to that element. Of course, on a site using jQuery (which is more than half the sites using JavaScript at all), looking at the handler will dump you into the jQuery event handling code, but it's a start.
Just as a side point: While it's fine to look at the source of pages for inspiration, or to see how they solved a particular problem, or what plugins they're using to get an effect, etc., I assume you're not grabbing large sections of their actual code (as opposed to libraries and plugins with liberal licenses) without their permission, which is probably not cool.

Chrome Developer Tools - Dynamically Created Element

Is there a way to find out which JS script created a dynamic element in Chrome's Developer Tools? If I do 'view page source' on the page, the element isn't there. I can see the element though in Chrome's Developer Tools. Is there a way to find out specifically which JavaScript file and what line in my JavaScript file created the element?
To help clarify: I know which element is created...what I don't know is which .js file created it and specifically what line in that .js file
Updated answer:
Below you've said:
I know which element it is...what I don't know is which .js file created it and specifically what line in that .js file
That's not how the question originally read. :-)
If you know which element it is, two options for you:
You can use Dev Tools to trigger a breakpoint when its parent element is modified:
Load the page
Open Dev Tools
Go to the Elements panel
Navigate to the parent element that the target element will eventually be added to
Right-click the parent element and click Break on... > Subtree Modifications
Now, Chrome will trigger a breakpoint when the parent element's subtree is modified, and so you can see what JavaScript code is adding the element.
Unfortuantely, it won't fire that breakpoint if the element is added during the main loading of the page (e.g., during the parsing of the HTML, by script that runs immediately rather than waiting).
If there's any text in the element that seems specific to it (content, id, class, some attribute, whatever), once the page is loaded you can use Chrome's powerful search feature to try to find that text:
Load the page
Open Dev Tools
Go to the Sources tab
Click Ctrl+Shift+F, which is "find in files" — it looks in all of the files associated with the page, not just the "current" file
Type the text that you think might help you identify the code adding the element
Press Enter, all matches will be shown below
You can even use regular expressions.
Original answer:
No, there's no simple way to differentiate an element created via JavaScript after page load from ones created by the initial HTML parsing.
Or at least, there isn't without adding JavaScript to the page that runs before any other JavaScript on the page runs, which I'm guessing is a requirement.
But if you can add JavaScript to the page before any other JavaScript runs, it's actually really easy to do:
Array.prototype.forEach.call(document.querySelectorAll("*"), function(element) {
element.setAttribute("data-original", "");
});
That marks every single element on the page with an attribute that tells you it was there when that code ran. You can see those attributes in the Elements panel of the Dev Tools. And so, if you see an element that doesn't have that attribute, you know it was added later.
document.querySelectorAll("*") is a big hammer you probably wouldn't want to use in production code, but for temporary use when debugging/developing, it's fine.
And if you want to know about the elements that have been created by other code later, you can do this in the console:
Array.prototype.forEach.call(document.querySelectorAll("*"), function(element) {
if (element.getAttribute("data-original") === null) {
console.log(element);
}
});
That'll output every element that wasn't on the page when you ran the earlier code, and Chrome's console is really cool — you can right-click the element display in the console and choose "Reveal in Elements panel" to see exactly where that element is.
You can use chrome-devtools-protocol's experimental feature.
Check this, https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getNodeStackTraces
First, send 'DOM.setNodeStackTracesEnabled' to chrome dev protocl.
Second, use 'DOM.getNodeStackTraces' message.
So, you can get call stack information from dynamic creation element.
I wrote my own program using these functions.
Image: https://imgur.com/a/TtL5PtQ
Here is my project: https://github.com/rollrat/custom-crawler

Deleting completely a html element

I am aware of .remove() , I am using it and its working fine, I mean its removing the element which I want. But I think it doesn't removes it permanently. On right clicking in browser window selecting View page source I am still able to see those removed elements.
I want to remove them completely or say permanently.
Please help.
.remove() removes them completely. The reason you still seem then in the view page source is because the page source does not change based on javascript. The page source shows how the page originally looked when it was first loaded, not how it currently is.
If you look in the developers console, you will see that they are no longer there.
Likewise, if you dynamically add a new element with javascript/jquery, it will not show that element in the page source.
Page Source and DOM are two different different things, whenever you edit the elements or remove them it get removes from DOM and not from page source. That means The javascript manipulate the DOM not the source which come from the server.
DOM: The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents.
The view source always shows the content came from the server initially without any modification. Use DEVELOPER CONSOLE in browsers to see the live DOM manipulation.
Note: Press F12 to enable console on major browser
view source render the code within the page that you have written(static)
for dynamic changes/view inspect the elements tab in developer tools.
View page source shows the content of the original HTML file, as returned by the HTTP server. The DOM can be altered with javascript, but the source will not change.
You Cannot permenantly remove the dom elements using jquery or javascript. .remove() is totally different from your logic. just it removes temporary hide from the dom elements suppose you refresh the page it comes again it is jquery magic.

How do I find what Javascript is running on certain events?

I'll pick Chrome for this example, but I'm open to a solution from any browser.
Use Case:
I have an update button on my website that is used to update item quantities in a shopping cart. I'd like to allow a user to enter a 0 and click update in order to remove the item. Trouble is, there is some listener in some js function that is denying the ability to enter a 0 and click update (after clicking update the old quantity remains).
My question is, what developer tool can I use to find which js function is running during that event? I don't think that Chrome's inspector does this, and I'm not very familiar with Firebug, but I couldn't find the functionality there either.
I feel that I should be able to inspect js firings just like I do css stylings. Is anyone aware of a tool I may use?
I've had to debug some particularly nasty unseen-cause Javascript issues at my job. Knowing the full depth of developer tools like Chrome's is definitely helpful. It undeniably takes some creativity to find places that might be causing the issue, but a few tips:
Tracking down event listeners
Under Chrome's Elements view, try Inspect-ing an element (right-click, Inspect); then, on the right side of the developer view, scroll down to Event Listeners. Here you can view what code files have hooked up an event. Often, this will just point you to a middle-framework from the really devious code you're looking for, but sometimes it will point you in the right direction.
Trapping a DOM modification
Many of the unwanted effects I see are because of something changing some value or attribute on the page that I don't want. Anytime this happens, you can right-click on the element (under the Elements view) and say "Break on..." and the specific scenario you're looking for. When Chrome then hits a breakpoint, you can then look downward in the Stack Trace until you find something recognizable that shouldn't be called.
EDIT after reaching ten votes!
Trapping a JS object modification
If the change you're interested in is code-internal, not in the UI, things get trickier. What's meant by this scenario is that you know somewhere in the code, something incredibly annoying like the following is happening.
company.data.myObject.parameter = undefined;
In this situation, you know myObject is still the same object, but it's being modified, perhaps unintentionally. For that, I often insert the following bit of code, sometimes just through the developer console at some point before said modification happens.
Object.defineProperty(company.data.myObject, 'parameter', {
set: (val) => {
debugger;
}
});
This includes an arrow function - you're only using this for debugging and Chrome supports it, so might as well save keystrokes. What this will do is freeze your debugger as soon as some line of code attempts to modify myObject's "parameter" property. You don't necessarily have to have a global reference to the variable if you can run this line of code from a previous breakpoint that will have the given object in the locals.
Otherwise, if all I'm starting out with is the HTML code, and I want to tie that to Javascript code, I'll often just look for identifying features like "id" elements, and search all JS files in my development directory for it. Normally, I can reach it pretty fast.
Open your page in Firefox with Firebug enabled.
Go to console tab in firebug and click profiling
enter 0 in the textbox and click the button.
Stop profiling.
You will be able to see all the javascript functions which have executed due to your actions. You can view them one by one to figure out which method has caused the mischief.
Go to you code. If you are using jQuery there is going to be a function that will be called with the class or id of that particular update button. Or, if you are using Javascript, there is going to be a function called inside the
<input type="button" name="update" onclick="update()">
These are the two ways to look for the function that is being called; there is no software that I know
Download Firebug for Mozilla Firefox, open it, click on Net and refresh your website. Than, you can see which files are loaded on the page.
If you want to check on errors and what goes wrong with an explanation, than click on console and refresh the page once again. You will see the errors and on which line it goes wrong.
Note: in your console, you can say hold or stop, so that the js file stops loading. And you can edit the script by clicking on script in Firebug. Debugging is simple, as it says on their official page https://getfirebug.com/javascript

Categories

Resources