0

I want to use the same class for div's as they serve the same purpose, although I cannot find a way to get it to work without outputing the same result to both of the div's.

JavaScript

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function divide(a, b) {
        $(this).text(a + " / " + b);
    }
</script>

HTML

 <body>
 <div class="division" ><script type="text/javascript">divide(3,7)</script>
 </div>
 <div class="division" ><script type="text/javascript">divide(12,75)</script>
 </div>
 </body>
4
  • Your code does not seem to work at all: jsfiddle.net/mZbp7 What do you think happens when you put the JavaScript statement into the div? Commented Nov 8, 2011 at 20:05
  • That's what I need help with, I thought if once it was called, JQuery's $(this). , would replace it with the text. Commented Nov 8, 2011 at 20:09
  • You are just calling a function, how should jQuery or JavaScript know which element it relates to? When calling a function this way, this will refer to the global object, which is window, it does not refer to any DOM element. Maybe you have to provide a better example, I don't see why you just don't write 3/7 and 12/75 in each div. Commented Nov 8, 2011 at 20:18
  • I can't just write it because I need to call those two parameters from a server. Commented Nov 8, 2011 at 20:20

4 Answers 4

3

simple

http://jsbin.com/ubodeg/edit#javascript,html,live

and if you want the actual result :

http://jsbin.com/ubodeg/2/edit

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

1 Comment

You don't need parseInt as the values are already integers. You should also include the code here imo.
1

In your example just write this

function divide(a, b) { return (a + " / " + b); }

2 Comments

I did this, but nothing seemed to happen?
How should this work? The returned value is not magically set as content of the divs.
1

You could change your divide function to return the string result instead of trying to use jQuery .text()

You could also update your divs to include IDs. Then inside your function, you could do:

$('#'+$(this).attr('id')).text(a + " / " + b);

That second way is far from idea however.

Comments

-1

give each div a different ID and pass that into your divide() method. Use the ID to differentiate between divs

3 Comments

Although I need to use classes.
As far as I know you can add a class and an ID to any element
if we put id to every element then why do we need to use classes ? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.