5

I'm iterating through a series of elements in jQuery (intentionally).

So basically I want something like this, but with the correct syntax:

$(".sonicrow").each(function() {
    $(this + 'somediv').css('background-color', 'red');
});

Obviously this is some kind of object/string mishmash. What would the correct syntax be for accessing the specific somediv within the this object?

Thanks, John.

John Hunt
  • 4,265
  • 8
  • 45
  • 59

4 Answers4

6
$(".sonicrow").each(function() {
    $('somediv', this).css('background-color', 'red');
});

Where the second parameter is the "context" of the selector. Of cause your somediv have to be .somediv if it´s a class or #somediv if it´s an id.

This question is related to How to get the children of the $(this) selector? which also contains this answer

...
    $(this).find('somediv').css(...)
...

According to jQuery context selector $(selector, context) is implemented with $(context).find(selector).

Community
  • 1
  • 1
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
1

Try this:

$(".sonicrow").each(function() {
    $(this).find('somediv').css('background-color', 'red');
});
qwertymk
  • 34,200
  • 28
  • 121
  • 184
1
$(".sonicrow").each(function() {
    $(this).find('.somediv').css('background-color', 'red');
});

you can do like this.

Mujah Maskey
  • 8,654
  • 8
  • 40
  • 61
0

Algorithm:

HTML structure is a tree structure. So when you refer $(".sonicrow") you reach to a node with "sonicrow" as a class name. Now you need to search the children nodes which is a div...

So your code will be something like this:

  1. Find elements having "sonicrow" class name
  2. Find any children element whose type is "div"...
  3. Apply css

Solution:

Find a reference to the nodes having "sonicrow" as class name: var route=$(".sonicrow");

Find child nodes which is a div: var desiredChild = route.find("div");

Apply css: desiredChild.css("property","value");...


Merge this into jquery chain:

$(".sonicrow").find("div").css('background-color', 'red');

But you want to repeat this for every element which has "sonicrow" class name, so you have to loop and your code becomes:

$(".sonicrow").each(function() 
{
    $(this).find("div").css('background-color', 'red');
});

P.S. I have used $(this) here because $(".sonicrow") has returned an object and you are traversing that particular object so you have to use "this" variable to point into that element.

On the other hand, you are using Jquery so $(this) gives you an jquery object to work this, otherwise you had to use basic javascript syntax like: this.style.css.property=value syntax :-)

I hope you have got your answer...

seoul
  • 864
  • 1
  • 12
  • 32