0

I have some HTML I want to process with jquery.

Pretty simple but I cannot get around getting all the elements with the same class:

<div class="myclass on"></div>
<div class="myclass off"></div>
<div class="myclass on"></div>

If I do this

$(".myclass")

I get only one. Any help?

EDIT

I actually only want the 'myclass on' to nest some html in each one to get this:

<div class="myclass on"><img src="bar.png"></div>
<div class="myclass off"></div>
<div class="myclass on"><img src="bar.png"></div>
5
  • 1
    $(".myclass") returns all element with the class myclass Commented Mar 29, 2013 at 2:14
  • 1
    That should work. What are you doing with it after that? Commented Mar 29, 2013 at 2:14
  • It is working jsfiddle.net/arunpjohny/zjErL Commented Mar 29, 2013 at 2:15
  • May be u did some. If you have done $('.myclass') it must work. Can you post what you have written. Commented Mar 29, 2013 at 2:15
  • Not quite good at writing JS, I did $(".myclass") in the Chrome inspector and only saw one. Commented Mar 29, 2013 at 2:17

4 Answers 4

2

Maybe you are just not combining two classes correctly in the selector? Because this works:

$(".myclass.on").html('<img src="bar.png">');

http://jsfiddle.net/zjErL/1/ (Thanks Arun for the initial jsfiddle)

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

Comments

1

Try using for manipulating each element separately. Just the class .on should be sufficient for the selector.

  $('.on').each(function(index){
    $(this).html('<img src="bar.png">');
  });

The documentation http://api.jquery.com/each/

2 Comments

I was really close and yet so far. Did not know how to traverse the array.
Using .myclass.on would be more safer than just using .on in this case though using .on also works like a charm.
1

May be u did some wrong. If you have done $('.myclass') it must work. Can you post your codes.

This works for me like a charm.

$(function(){
    $('.myclass').SOMEEVENT(function(e){ // or use div.myclass without problem 
        // do something. It must work.
    });
});

OR if you want to iterate through each element, you can use .each

$(function(){
    $.each($('.myclass'),function(ind, val){
        // do something.
    });
});

OR if you want to use additional class like .on or .off

$(function(){
    $.each($('.myclass.on'),function(ind, val){
        // do something.
    });
});

EDIT:
To add image to myclass on, you can simply do this

$(function(){
    $('.myclass.on').html('Your NEW Adding Tag here');
});

Comments

0

$(".myclass.on").css('color', 'red');

Should select elements with both classes.

Comments

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.