views:

31

answers:

3

I'm trying to select the H2 that contains the most characters, or is the widest in width, whichever one is simpler, or if you know how to do it could you put both? I'm not sure of the syntax.

+1  A: 

To get the pixel-widest, you could just loop though kind of abusing the .width() function, for example:

var cw = 0, widest;
$("h2").width(function(i, w) { if(w > cw) {widest = this; cw = w;} return w; });
//widest == widest h2 element
//$(widest).addClass("widest");

You can test it out here. Inside this function w is the current width, so we're just seeing if it's wider than our current widest, and if so setting the current width to the new widest and widest to the current <h2> that was found to be wider than the previous widest.

You can do something similar for character count using .text():

var cw = 0, widest;
$("h2").text(function(i, t) { if(t.length > cw) {widest = this; cw = t.length;} return t; });
$(widest).addClass("widest");​

You can test that version here.

Nick Craver
A: 

They're both pretty similar, you'll have to iterate through each one and check for each length or width. Something like

var maxWidth = 0;

function getLongest(){
  var elementWidth,
    domNode;

  $("h2").each(function(i, element){
    elementWidth = $(element).width();
    if (elementWidth > maxWidth){
      domNode = element;
      maxWidth = elementWidth;
    }
  }
  return domNode;
}

You can substitute $(element).width() for $(element).text().length and rename vars appropriately.

Note that if 2 elements have the exact same width, this will only select the first one.

brad
A: 
$(document).ready(function() {
    var longestH2 = null;
    $("h2").each(function(k, v) {
        if ($(v).width() > $(longestH2).width() || longestH2 == null) longestH2 = v;
    });
    $(longestH2).css("border", "3px solid red");
});
harpax