sports - title-- -- > {} third-- -- > undefined - javascript

i am new to js
Around eight hours I am trying to debug why I am getting the below empty object
document.getElementsByClassName("sports-title") is working fine in fiddle but when I put in my code base its not working fine.
it is returning like this so I am not able to proceed.
codebase output
sports - title-- -- > {}
third-- -- > undefined
fiddle ouput
sports-title---->{"0":{}} third---->{}
I am using same html structure.
can you guys tell me what could be problem so that I can proceed.
findStringInsideDiv() {
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}

If document.getElementsByClassName("sports-title") isn't returning any elements this could mean:
Your HTML source doesn't have any elements with class="sports-title", possibly because of a syntax error, spelling error, etc.. Try inspecting your web page with a browser's DOM inspector and look for the elements which you think should be in the sports-title class.
Or
Your Javascript is executing before the .sports-title elements are actually added to the document, because scripts are (normally) executed synchronously during document parsing, as soon as the parser encounters them. Try moving the <script> element to the end of the <body>, after all the other elements are defined.
There may be other possible causes that I can't think of right now.

This probably isn't the answer but I can't leave a comment so here goes:
I was messing with your jsFiddle and I noticed that if you change JSON.stringify(object) to object.ToString that they turn into undefined. So my question to you is are you sure you're code in your codebase matches the jsfiddle?
Also if you're using JSfiddle to make and test your code first, you might consider installing Brackets.io. It has a nifty live update feature that makes web development easier for beginners and it opens up a preview on the browser. I've noticed in the past that JSfiddle doesn't always operate the same as a browser.

Related

How do I get document.getElementsByTagName('').innerHTML to make text between 2 tags?

I'm trying to use JavaScript to include a footer on several webpages, so if I want to change the footer, I only have to change it in one place. PHP is not available on this server and neither are server side inserts (SSI), but Perl, Python, and Tcl are available. I have been trying with document.getElementsByTagName('footer').innerHTML = "text"; but it doesn't produce text. I copied this code from dev.mozilla, and it tells me how many tags I have:
var footer = document.getElementsByTagName('footer');
var num = footer.length;
console.log('There is ' + num + ' footer in this document');
So, I don't know what's wrong with the innerHTML script. I also tried with paragraph tags and got the same results in both cases.
I reccoment using textContent instead. Se why here.
To see how it works, paste the following into your browser console while you're on StackOverflow and hit enter.
document.querySelector('.site-footer').textContent = 'Custom footer content.'
note: use querySelector with a class instead of getElementByTagName
Cheers! 🍻
Before asking this question, I had searched for Python includes without any luck, so I stopped there, but after asking this question, I thought that I should search for Perl/Ruby includes. Today, I found out that I can use the Perl use function, so I could study that and try to implement it although I am completely new to Perl. Ruby also appears capable, perhaps even more. I have no experience with Ruby either, but maybe I should start there.
I just figured out that getElementsByTagName() results in an array, so I have to refer to the footer's index with [0]:
var footerTags = document.getElementsByTagName('footer');
footerTags[0].innerHTML = "test";

Search on page with javascript

I have a html page, and I want to find on it some data, but main trouble is that page is generated on server, and I want to write javascript code on my local machine and run it. So how can I write and run on local machine javascript code, so that it will find text, or get element by id/class?
Note, this is important: only pure javascript, no libraries like jQuerys and etc!
Thank you.
Updated answer:
I didn't understand at first that you want to call up a web page you're not in control of, and then use JavaScript in your browser to interact with it.
The information in the original answer below is still relevant, but the question is: How do you make the code run in the right context? And the answer is: There are at least two ways:
Any decent browser these days has built-in debugging tools. Look on the menus for them, but in many browsers they're accessible via the F12 key or Ctrl+Shift+I. In those tools, you'll find a "console" where you can type JavaScript and have it run in the context of the page you're looking at.
This is great for doing things interactively, but it's a bit of a pain to retype it every time. You can also put the code in a local file (say, /home/tjc/foo.js) and then when you go to the page, use the console to append that script to the page (which will cause it to execute, within the context of the page), like this:
document.documentElement.appendChild(document.createElement('script')).src = "file:///home/tjc/foo.js";
Once you have your script doing what you want, you might want to turn it into a bookmarklet. This is a browser bookmark using the javascript: scheme rather than the usual http: and such. See the link for details. You'll want a tool that takes your JavaScript code and does the necessary URL-encoding for you, like the Bookmarklet Crunchinator or similar.
Original answer:
... so that it will find text, or get element by id/class...
Those are three very different questions:
To find text on the page, you have a couple of options:
If you only want to find the text but don't much care exactly what element contains it, you can just look through innerHTML on document.body. innerHTML is a string; when you access it, the browser creates an HTML string for all of the DOM elements in the element you call it on (and its descendants). Note that this is not the original content from the server; this is created on-the-fly when you access the element. For a lot of use-cases, getting this string and then looking through it could be useful. Note that the text you're searching through is markup, so for instance, if you searched for the word "table" you might find it in a sentence ("We sat down at the table.") or in markup (<table>...).
Here's an example of counting the word I'm on the page using innerHTML: live copy | source - See note about examples at the end.
(function() {
var pageText = document.body.innerHTML;
display('Count of "I\'m" on the page: ' +
pageText.match(/I'm/g).length);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
If you need to find out exactly what element it's in, you'll need to write a recursive function that walks through the nodes of the page and, for Text nodes, looks at the text within. Here's a basic example (the function is the walk function): Live copy | source - See note about examples at the end.
(function() {
var matches = [], index;
walk(matches, document.body, "");
function walk(matches, node, path) {
var child;
switch (node.nodeType) {
case 1: // Element
for (child = node.firstChild; child; child = child.nextSibling) {
walk(matches, child, path + "/" + node.tagName);
}
break;
case 3: // Text
if (node.nodeValue.indexOf("I'm") !== -1 ) {
matches.push("Found it at " + path);
}
break;
}
}
display("Matches found (" + matches.length + "):");
for (index = 0; index < matches.length; ++index) {
display(matches[index]);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
To find an element on the page by id, use document.getElementById.
To find an element on the page by class, on most modern browsers you can use either getElementsByClassName or querySelectorAll.
Note about the examples: I'm using JSBin, which puts the JavaScript you see on the left-hand side in the "source" view at the end of the HTML you see on the right (just before the closing </body> tag), by default. This is in keeping with best practices.
Reading:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
If you are looking for imacros solution, then it'some like this:
var reportDataTable = window.content.document.getElementById("yoursid");
if (reportDataTable == null)
{
iimPlay("mac1.iim");
}
else
{
iimDisplay("stop!");
}
Where mac1.iim is macros, which would repeated, until
window.content.document.getElementById("yoursid");
will not be founded

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

ASP.NET inline server tags

I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.
So I have code like this in my .aspx file:
function EditRelationship() {
var projects=<%= GetProjectsForEditRelationship() %>;
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
var rels=<%= GetRelationshipsForEditRelationship() %>;
// etc
}
Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.
I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).
So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.
If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?
Create a ASP:HiddenField control, set its ClientIdMode to "Static"
Assign the value of GetRelationshipsForEditRelationship() to this field on page load
In your javascript, read the value from the hidden field instead, I assume you know how to do this.
It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)
You could do this from your page in the code-behind
ClientScript.RegisterArrayDeclaration("projects", "1, 2, 3, 4");
or to construct something like JSON you could write it out
ClientScript.RegisterClientScriptBlock(GetType(), "JSONDeclarations", "your json stuff");
UPDATE Based on my comment
<script id="declaration" type="text/javascript">
var projects=<%= GetProjectsForEditRelationship() %>;
var rels=<%= GetRelationshipsForEditRelationship() %>;
</script>
<script type="text/javascript">
function EditRelationship() {
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
}
</script>
I don't have VS2008 installed to test with, so take this with a grain of salt, but have you tried something like this?
var projects = (<%= GetProjectsForEditRelationship() %>);
Something like that might trick the JavaScript parser into ignoring the content of your expression.
For what it's worth, VS2010 correctly parses and highlights your original code snippet.
Is it an option to move this to VS2010? I just copied and pasted your code and the IDE interpreted it correctly.
The best solution is to put javascript in a separate file and avoid this entirely. For this particular function, you're doing server-side work. Why not build the list of options that you intend to add dynamically in codebehind, put them in a hidden div, and then just have jQuery add them from the already-rendered HTML?
If you have a situation where you really want to dynamically create a lot javascript this way, consider using ScriptManager in codebehind to set up the variables you'll need as scripts and register them, then your inline script won't need to escape
ScriptManager.RegisterClientScript("projects = " + GetProductsForEditRelationship());
(Basically, that is not the complete syntax, which is context dependent). Then refer to "projects" in your function.
(edit)
A little cleaner way to do this on a larger scale, set up everything you need like this in codebehind:
string script = "var servervars = {" +
"GetProductsForEditRelationship: " + GetProductsForEditRelationship() +
"GetRelationshipsForEditRelationship: " + GetRelationshipsForEditRelationship() +
"}"
and refer to everything like:
servervars.GetProductsForEditRelationship
If you do this a lot, of course, you can create a class to automate the construction of the script.

How to increase speed of getElementById() function on IE or give other solutions?

I have a project using Javascript parse json string and put data into div content.
In this case, all of itemname variables is the same div's id.
If variable i about 900, I run this code in Firefox 3 for <10ms, but it run on IE 7 for >9s, IE process this code slower 100 times than Firefox
I don't know what happen with IE ?
If I remove the line document.getElementById(itemname), speed of them seems the same.
The main problem arcording to me is document.getElementById() function?
Could you show me how to solve this prolem to increase this code on IE ?
Thank in advance.
var i = obj.items.length-2;
hnxmessageid = obj.items[i+1].v;
do{
itemname = obj.items[i].n;
itemvalue = obj.items[i].v;
document.getElementByid(itemname);
i--;
}while(i>=0);
Are you really noticing any latency?
gEBI is natively very very fast, I don't think you can avoid it anyway for what you're doing. Could you provide a low-down of what you're doing precisely? It looks like you're using a loop, but can you post exactly what you're doing inside of the loop, what your common goal of the script is?
document.getElementByid(itemname) is the fastest way to get a single element from the DOM in any real application you will sould not see any problems with using it, if you do see a problem you need to rethink you code a little it possible to acomplish any task with just a handfull of calls for this method. You can present you full problem if you like so I could show you an example
At least cache the reference to document:
var doc = document;
for(;;) {
doc.getElementById(..);
}

Categories

Resources