0

I am wondering if there's any way to make this possible. I want to to check if the text value of an element begins with a certain letter.

This is my non working code:

if ($('title').text().substring(0, 1) === 'W') {
        $('body').css('background', '#27aae2');
}
9
  • Can you please post the #element html ? Commented Apr 21, 2015 at 20:48
  • 2
    Works for me -> jsfiddle.net/adeneo/sh9kh7ty, indexOf would probably be easier ? Commented Apr 21, 2015 at 20:49
  • Your code should work. Commented Apr 21, 2015 at 20:49
  • Should work. jsfiddle.net/rt5n76mq Commented Apr 21, 2015 at 20:50
  • 1
    document.title gets the title as a string. No need to overuse jQuery for that. Commented Apr 21, 2015 at 20:55

2 Answers 2

3

you can try like this:

if(yourString.indexOf('A') === 0) {
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why search the entire string when you can just test the first letter, like the original code does?
If you're going to optimize that part, do yourString[0] == 'a'
@arcyqwerty so long as the programmer is aware yourString[0] may be undefined (use ===)
undefined == 'a' would be false as expected, same as your implementation (-1 !== 0).
0

Yes this work, see code snippet below. Please note it was created based on your original post.

$(document).ready(function() {
  if ($('#element').text().substring(0, 1) === 'A') {
    alert('Do something useful')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element">A hello</div>

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.