Muskogeee
Muskogeee

Reputation: 141

What am I doing wrong running a jquery function on each item of a class?

I'm trying to make a line separator that will have a bit of text as a title and then follow the text with a strike-through to the edge of the page. I thought I was writing the bit of jquery properly to call the function on each instance of my separator div but apparently I'm not.

Here's what I thought it should be:

$(".separator").each(function() {
    var linewidth = 706 - $(".s-text").width();
    $(".s-line").width(linewidth);
}); 

See fiddle here: http://jsfiddle.net/WY7tL/

Upvotes: 1

Views: 144

Answers (3)

Jeff Noel
Jeff Noel

Reputation: 7618

Solution

You must specify which .s-text element you want to select, in this case, the child of the selected .separator.


Explanation

$.each(), or $('selector').each() will loop through all the elements corresponding to the selector query that you provide it.

Each time it goes into the loop, the specific element corresponding to the index of the array of corresponding elements is selected and assigned to the variable this.

this is a DOMElement, not a JQuery object. This is why we put it within parenthesis, calling the JQuery ($) object on it: $(this).


JavaScript/jQuery

$(".separator").each(function() 
{
    var linewidth = 706 - $(this).find(".s-text").width();
    $(this).find(".s-line").width(linewidth);
}); 

Pure JavaScript

var sep = document.getElementsByClassName('separator');
for (var i in sep)
{
    if(sep[i].nodeType==1)
    {
        var linewidth = 706 - sep[i].querySelector('.s-text').offsetWidth;
        sep[i].querySelector('.s-line').style.width = linewidth+"px";
    }
}

JQuery Live Demo

Pure JavaScript Demo

Performance comparison

Upvotes: 8

NDM
NDM

Reputation: 6830

You need to fetch the relevant element from inside your .separator by calling find() on it

$(".separator").each(function() {
    var linewidth = 706 - $(this).find(".s-text").width();
    $(this).find(".s-line").width(linewidth);
}); 

Upvotes: 0

Sindhara
Sindhara

Reputation: 1473

http://jsfiddle.net/WY7tL/1/

You have to call $(this).children('.class') Look at the code in the fiddle

Upvotes: 1

Related Questions