0

Hey guys I'm a noob to jquery and I've heard it's okay to mix jquery with pure javascript, but I'd like to know if that is what's causing the following code not to work or is it something else that I'm doing wrong?

var fnd_child = $('#thumb_slider').children().length;

$(document).ready(function(){
    $('#basic_div').innerHTML = fnd_child;
});

Nothing happens in in basic_div... it's just empty. I've even tried attaching this function to a button but still nothing happens. I just need to know how many children are in basic_div and then print that number out on the screen. Thanks!

2
  • 1
    mix js with javascript js = short for JavaScript. You mean jQuery .. but then jQuery is javascript as well.. Commented Mar 21, 2012 at 0:22
  • yes I mean javascript but .innerHTML is just javascript... it's not part of the Jquery api so I was wondering if that was causing a problem. Commented Mar 21, 2012 at 0:25

4 Answers 4

4

$('#basic_div') is a selector that returns a jQuery object, not a DOM element.

$('#basic_div')[0] will get your element, but why not use $('#basic_div').html() instead?

Sign up to request clarification or add additional context in comments.

Comments

1

It is always safe to access dom elements inside the document ready. This assures that it will be accessed once the dom is loaded . You just use the html method to set the value. It should be working.

$(document).ready(function(){
    var fnd_child = $('#thumb_slider').children().length;
    $('#basic_div').html(fnd_child);
});

Here is the working demo : http://jsfiddle.net/vrfAZ/

Comments

1

You should use the .html() method.

$('#basic_div').html(fnd_child);

and even better (since fnd_child is just text) use the .text() method

$('#basic_div').text(fnd_child);

Comments

0

You can also do:

document.getElementById('basic_div').innerHTML = fnd_child;

Calling the jQuery function with a selector returns a "jQuery object" that holds the elements selected by the selector in an array. It then has methods to replace equivalent DOM methods, plus more methods to set or return element properties (or sometimes attributes).

So for the jQuery version, instead of assigning to the innerHTML property, you must call the html method and provide the replacement HTML as a parameter:

$('#basic_div').html(fnd_child);

which essentially just does what the line above does, but with many more function calls.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.