0

I am passing div name in the query string from one html page and retrieving that div name on the other html page. Now I want to display that specific div on the page.My code is

function onLoad()
{    
    var divname=window.location.search.substring(1);    
    document.getElementById(divname).style.display="block";    //error is in this line
}

But I am getting an error as "object expected". please help me

Chase Florell
  • 46,378
  • 57
  • 186
  • 376

3 Answers3

3

The window.location.search property returns the part of the URL that follows the ? symbol, including the ? symbol.

So for example it might return ?paramname=paramvalue. When you call substring(1) on it you get paramname=paramvalue which is what gets passed to the document.getElementById function which obviously is wrong because such element does doesn't exist on your DOM.

You could use the following javascript function to read query string parameter values:

function onLoad() {    
    var divname = getParameterByName('divname');    
    document.getElementById(divname).style.display = 'block';
}

This assumes that you have a query string parameter name called divname:

?divname=some_div_name

Adjust the parameter passed to the getParameterByName function if your query string parameter is called differently.

You might also want to introduce error checking into your code to make it more robust:

function onLoad() {    
    var divname = getParameterByName('divname');    
    var divElement = document.getElementById(divname);
    if (divElement != null) {
        divElement.style.display = 'block';
    } else {
        alert('Unable to find an element with name = ' + divname);
    }
}
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I have copied this code as it is but I am getting an error on line no 2 in "onLoad()" function, it says "object expected" – user1838922 Jan 26 '13 at 18:15
  • Did you declare the `getParameterByName` function? I have linked to it in my answer: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values/901144#901144 Make sure that this function is declared before using it. – Darin Dimitrov Jan 26 '13 at 18:17
0

What I am suggesting is place your js at the end of the html code (before </body> tag). Do not use a function.

<html>
    ...
    ...
    ...
    <body>
    ...
    ...
    ...
        <script>
            var divname=window.location.search.substring(1);    
            document.getElementById(divname).style.display="block"; 
        </script>
    </body>
</html>  
New Developer
  • 3,245
  • 10
  • 41
  • 78
0

I have re-written my function and it is working, code is like this

function load()  
{  
    var divname = window.location.search.substring(1);  
    var params=divname.split('=');  
    var i=1;  
    alert(params[i].substring(0));  
    document.getElementById(params[i].substring(0)).style.display='block';  
}
New Developer
  • 3,245
  • 10
  • 41
  • 78