Build Thread

5 posts

Passing CSS selector as Parameter ?

Back to Forum: Build
  • User profile image
    Chauhan

    I am trying to pass dynamic id to querySelector(), but it doesn't work. Refer code below:
    document.querySelector("#onlineDashboard").onclick = showHide;
    function showHide() {
    if (document.querySelector("#"+this.id+">div").getAttribute("class" == "hide") {
    document.getElementById("onlineDashboardContent").classList.remove("hide");
    document.getElementById("onlineDashboard").innerHTML = document.getElementById("onlineDashboard").innerHTML.toString().replace("+", "-");
    }
    else {
    document.getElementById("onlineDashboardContent").classList.add("hide");
    document.getElementById("onlineDashboard").innerHTML = document.getElementById("onlineDashboard").innerHTML.toString().replace("-", "+");
    }
    }

    Please tell me why it doesn't works.
    And also suggest some way to pass dynamically created valid CSS selector to querySelector();

  • User profile image
    calingasan

    It's always good to check if you are getting the correct parameter you want to use in a function before you use it.  On your showhide function try this.

    function showHide() {
      console.log(this.id);
      //... the rest of the code
      //...
      //...
    }

    check your console log if you are getting the correct id?

    Another thing I would change is the use of querySelector for selecting elements by id, just as a personal preference, I would rather go like document.getElementById("dynamic_id_here").querySelector("div").

    Hope you get to fix it.

  • User profile image
    calingasan

    @Chauhan:

    I'm looking at your code again and noticed this section

    if (document.querySelector("#"+this.id+">div").getAttribute("class" == "hide") {
       //.....
    }

    Try this instead

    if (document.querySelector("#"+this.id+">div").getAttribute("class") == "hide") {
      //...
    }

    Probably a typo on your end but you forgot to close the getAttribute's "(rounded brackets)"

     

  • User profile image
    Chauhan

    @calingasan:

    Thanks for suggestions. It helped me in fix my code.

  • User profile image
    Carlhartley

    At the every time it is the necessay task to check whether the parameter is corrent or going wrong. You have to select the correct one before using. cheap website design india

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.