52

I seem to be having trouble with my code. I need to say:

if ( $('html').attr('lang').val() == 'fr-FR' ) {
    // do this
} else {
    // do that
}

When I check the console, I just get an error telling me this isn't a function. Help would be appreciated.

Thanks,

2
  • 1
    You should be using data() for this sort of thing. Commented Jun 26, 2012 at 15:55
  • 1
    No. Html does have a attribute called lang. Commented Jun 26, 2012 at 15:58

2 Answers 2

112

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}
Sign up to request clarification or add additional context in comments.

2 Comments

You answered to quickly dude, I have to wait 5 more minutes in order to accept it :)
You often want to check the class attribute for a value, but class attr can have multiple values separated by space, like this <div id="mydiv" class="one two three"></div> so in that case you can use the function hasClass() to check for a value like so $( "#mydiv" ).hasClass( "two" )
14

jQuery's attr method returns the value of the attribute:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

All you need is:

$('html').attr('lang') == 'fr-FR'

However, you might want to do a case-insensitive match:

$('html').attr('lang').toLowerCase() === 'fr-fr'

jQuery's val method returns the value of a form element.

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

1 Comment

Very thorough, great response. Thanks.

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.