1

I'm setting a variable to the contents of a h1 tag on my site. I want to write an if statement which tests to see if there is a specific word inside that h1 tag. I need to set a dropdown based on the title of the form.

So, I have this html.

<div id="booking-details"><h1>This is Los Angeles</h1></div>

Here is the jquery:

var city = $('#booking-details h1').text();
if (city.text().indexOf('Los Angeles') >= 0)) {alert("This city is Los Angeles")};

I'm getting a syntax error and not quite sure how to pull the index of the text from the variable.

Thanks in advance for any help.

4 Answers 4

3

I don't think that you can get the text() of the text(). Have you tried:

var city = $('#booking-details h1');
if (city.text().indexOf('Los Angeles') >= 0)) {alert("This city is Los Angeles")};
Sign up to request clarification or add additional context in comments.

Comments

0

You are using text() twice, just do:

var city = $('#booking-details h1').text();
if (city.indexOf('Los Angeles') >= 0)) {alert("This city is Los Angeles")};

Or:

var city = $('#booking-details h1');
if (city.text().indexOf('Los Angeles') >= 0)) {alert("This city is Los Angeles")};

1 Comment

This worked like a charm, except I had an extra parenthesis in there which was causing the syntax error.
0

You are doing city.text() when you already set city to $('#booking-details h1').text();?

Use

var city = $('#booking-details h1');
if (city.text().indexOf('Los Angeles') >= 0)) {alert("This city is Los Angeles")};

Comments

0

...I'm a bit late, but for others who'll find this via google, try the pure jQuery attempt:

HTML

 <div id="booking-details">
     <h1>The city of Los Angeles</h1>
 </div>

jQuery

var city = 'Los Angeles';
if ($('#booking-details h1:contains("' + city + '")').text().length)
    alert('Welcome to ' + city);

Test it on jsfiddle.net

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.