Reputation: 141
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
Reputation: 7618
You must specify which .s-text
element you want to select, in this case, the child of the selected .separator
.
$.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)
.
$(".separator").each(function()
{
var linewidth = 706 - $(this).find(".s-text").width();
$(this).find(".s-line").width(linewidth);
});
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";
}
}
Upvotes: 8
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
Reputation: 1473
You have to call $(this).children('.class')
Look at the code in the fiddle
Upvotes: 1