3

I have the following function, which should return different values based on the head's text:

function getPage(){
  var page;
  var headText = $.trim($('h1').text());

if(headText=="Page 1"){
    page= 'a';
}else if(headText=="Page 2"){
    page= 'b';
}else if(headText=="Page 3"){
    page ='c';
}else if(headText=="Page 4"){
    page= 'd';
}else{
    page= 'ERROR';
}

return page;
}

Unfortunately, the function only returns "ERROR". I've tried it without the trim method. I've tried it by writing Page 1 - Page 4 into variables of their own and comparing 2 variables in the if() section. Nothing works. Where is my error? (I am certain that the text of the < h1>- Element is "Page 1", "Page 2", "Page 3" or "Page 4")

ikts
  • 45
  • 6

2 Answers2

1

Your code works fine if there is only one h1 tag on your page. If there are multiple h1 tags then their text will be concatenated in headText.

You should uniquely identify your h1 tag with an id attribute to get only that tag's text.

ethan
  • 111
  • 1
  • 8
  • That's correct but doesn't explain why it doesn't work: `I've tried it by writing Page 1 - Page 4 into variables of their own and comparing 2 variables` – A. Wolff May 16 '16 at 15:40
  • Sure it does. It doesn't work because $('h1') selects all the h1 tags and when you call $('h1').text() all the their text is concatenated together. See: https://plnkr.co/edit/vOYnZohkjTEu4q634JUV – ethan May 16 '16 at 15:48
  • But OP said he had tested it setting text in variable and still doesn't work. So obviously the issue is somewhere else – A. Wolff May 16 '16 at 15:49
1

First, console.log(headText); to see what you're actually getting.

You may be getting the text of the h1's children added onto the text of the h1 - see http://api.jquery.com/text/, specifically

Get the combined text contents of each element in the set of matched elements, including their descendants. [emphasis mine]

If that's the case, see this question and answer for a solution.

Community
  • 1
  • 1
Sander Moolin
  • 450
  • 4
  • 11