getElementsByClassName not finding uls - javascript

I am unable to get my code working correctly in Chrome however when I paste my code into JSFIDDLE it works correctly. I am trying to get all ul tags in the document using getElementsByClassName and then all lis within the one of the uls. When I use getElementsByClassName("ul") it is finding none in Chrome, however if I remove either one of the two divs before the uls getElementsByClassName("ul") finds all of them so the divs seem to be what is breaking the JS.
I was unable to reproduce the problem in JSFIDDLE as the code worked correctly there but here it is: http://jsfiddle.net/zTP9H/
var sElements = document.getElementsByClassName("HeaderWrapWide");
var catOne = document.getElementsByTagName("ul");
alert("number of ul: " + catOne.length);
var liTags = catOne[3].getElementsByTagName("li");
alert("number of li: " + liTags.length);
Thanks
Alex

are you sure you are running this javascript AFTER the html is added to the page? jsfiddle probably renders html/scripts in a different way to your webpage and hence that is why it works there. If your javascript is in the head part of your HTML you could well have this behaviour - try using jquery on document ready function http://api.jquery.com/ready/ or move your JS to the bottom of the page
I cant see anything wrong with your code

I guess you have the above JS code within your head tag. So wrap it with Immediate function invocation
(function () {
//ToDos
})();
JSfiddle

If you want to execute the code in the <head></head>
like you have it, then try wrapping your code in a
function like this if you don't want to use jQuery.
Also, this doesn't work in IE so check caniuse.com/#search=DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
your code here.
})

Related

error in converting js code to jQueryMobile

I have a javascript/jquery code http://jsfiddle.net/9773D/ for timer.
I am trying to port it to jQuery Mobile code but I am confused about the pageinit,bind,live etc window events.
In the code i see that the error is because some elements in the tick() function are not loaded in DOM before it has been invoked in the code. Can someone help me in correcting my code.
Thanks,
I changed your line to
var timeDisplay = $(".time")[0];
and that fixes it.
Edit:
Adding explanation:
Since you used innerHTML instead of $('.time').html(""), you needed to set timeDisplay to the HTML node, since innerHTML is a property of the node, not the jQuery object that is returned by the selector $('.time').
Here's a jsfiddle that shows how it could be done in a more jquery'sh way. http://jsfiddle.net/9773D/1/
timedisplay.innerHtml = "" //does not work since timedisplay is a jquery object
//timedisplay[0] is the html object so on that innerHtml does work
But jquery has the function .html("");
timedisplay.html(""); // is a bit cleaner

using javascript to output html

I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.
alert("beginning");
//var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
//$('body').append(link);
//document.write("hi");
//document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("before function");
(function(){
alert("middle");
var links = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(links);
alert("after middle");
//alert($("img").attr("id"));
document.write("hi");
document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("end");
}());
I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.
Also, is this the correct way for jquery?
Thanks in advance!
Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.
You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :
$(document).ready(function(){
/* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
or the shorthand version that does same thing:
$(function(){
/*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.
There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here: http://docs.jquery.com/How_jQuery_Works
Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.
It is unnecessary to wrap your html in a JQuery object (in this case):
var links = "<a href='http://juixe.com'>Hello, <b>World</b>!</a>";
$('body').append(links);
or simply:
$('body').append("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:
$("body").html("/*Your HTML here*/")
At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.

list changing with javascript

I'm using MooTools.
I have a ul element:
<ul id="alerts"></ul>
And I can access it with $("alerts"), but when I try to change it by doing:
$("alerts").innerHTML += "<li>word</li>";
In a for loop, it only does the first... It doesn't add any more li tags. Full code here: rightandrong.info/Upload.html. I've modified it so it doesn't actually upload.
Drag and drop multiple files, and it should tell you when each one is done in the ul. What's wrong?
EDIT: Checking the full code is recommended.
That's why you can't do it
Regarding your problem: on the js fiddle I did it's working, are you sure the loop contains something more than one element? (on your example it's working too)

jQuery - dynamically remove head elements on click

Does anyone know if you can remove head elements on a button click and how to do it with jQuery?
I am trying to get rid of certain script tags from the html head when a button is clicked.
For instance. I have 1 screen view with a slideshow controlled by an external javascript file. When I click on a button "Click to get rid of this elements JS" I want to remove the external javascript path from the HTML Head.
Any ideas. Have been at this thing for a week or so.
You can add an id to a script element then remove that ID:
<script type="text/javascript" src="init.js" id="initJs" ></script>
<span id="removeScript"></span>
$('#removeScript').click(function() {
$('#initJs').remove();
});
You can do this sort of thing using javascript, sure, but before you do it, you might want to ask yourself again why. Here's a link describing how to do it in pure javascript with a jquery example provided by the other answerer:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
But try to keep in mind that most modern browsers will keep these external resources in memory for at least as long as the page is open. Therefore, you won't really be doing much.
I don't think its a good Idea to remove Entire HEAD Element. 'Cause your Page may contain some more Elements (i.e., title, style..) which are appended to Head Element. If you want to remove a particular script Element do something like
$(function() {
$('input[type=button]').click(function() {
$('script[src=path/file.js]').remove();
});
});
Edit :
var flag = false;
function breakTheCode() {
if(!flag) {
//run your code
}else return;
}
$(function() {
$('input[type=button]').click(function() {
flag = true; //flag is set, so we no more using/ running your code
breakTheCode(); //call you function/method
});
});
For my part the best solution is to use ID on the scripts.
I read many page over the web, try many solutions, and the only one who works fine every time is to remove a script like a div with an id !
For remove js file : $("script[src='your.js']").remove();

jQuery objects don't work

When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD

Categories