0
function url_info()
{
    var url_val=document.getElementsByClassName("spc-tab");
    var current_s=0;
    for(var i=0;i<url_val.length;i++)
    {
        var url_class=url_val[i].className.split(" ");
        if(url_class[1]!=null)
        {
            if(url_class[1]=="selected")
            {
                current_s=i;
                break;
            }
        }
    }
    var temp_1=url_val[current_s].text;          //**Error here**
    return(temp_1);
}

In this function url_info i am getting the TypeError But i don't know why?? .... as My var current_s is defined within the scope and integer...

21
  • 1
    it's not an array, it's a HTML Collection Commented Jul 14, 2018 at 9:30
  • not sure what an elements text property is supposed to be though! Commented Jul 14, 2018 at 9:33
  • 2
    All of this code can be reduced to document.querySelector(".spc-tab.selected").textContent;. Commented Jul 14, 2018 at 9:37
  • 1
    @Lokesh "so . won't work here" - What?? that makes absolutely zero sense ... your point was that it was an array ... it isn't Commented Jul 14, 2018 at 9:42
  • 1
    so, document.getElementsByClassName("spc-tab") is returning an empty HTMLCollection ... which is why you get the error ... you're probably calling url_info before any elements with that class exist - which is a common error, trying to run javascript before the page loads Commented Jul 15, 2018 at 0:36

1 Answer 1

1

why write this much of code when one line can do:

function url_info() {
  var temp_1 = "";
  var url_val = document.querySelector(".spc-tab.selected");

  temp_1 = url_val[0].text > 0 ? url_val[0].text : temp_1; 
  return (temp_1);
}

and second, you don't require to convert your class name to string then split. You just can access them through classlist. Then use contains.

function url_info() {
  var url_val = document.getElementsByClassName("spc-tab");
  var current_s = 0;
  for (var i = 0; i < url_val.length; i++) {
    var isSelected = url_val[i].classList.contains("selected");
    if (isSelected) {
      current_s = i;
      break;
    }
  }
  var temp_1 = url_val[current_s].text; 
  return (temp_1);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

I don't Know why My code is not working in Html file ...... it is working fine when I am adding it in console ..But in Html file it gives error and it is showing me url_val correct ... but after that i tried to check url_val.length and it is giving me 0 .... but when I printed the url_val on console same script but with console.log(url_val) it is showing me HtmlCollection with 8 entries....

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.