• 0

[Javascript] Add onclick event to button which has random ID


Question

Hi all,

Got a website on squarespace which unfortunately is somewhat limited when it comes to adding code to buttons. An onlick would be ideal and I can add it via javascript HOWEVER the damn div ID changes each time the page is generated.

I need to somehow use js to search the page, find the button which has particular text in it and then I can use document.getElementById("ETC").onclick to perform what I need.

My head hurts just thinking about this.

Any clues?

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

If you can use jquery and want to select based on the content: https://api.jquery.com/contains-selector/

Also if the id value is something like "yolo-button-546366" you could use the following selector: "button[id^=yolo-button-]"

using [ ] to select elements with properties in combination with ^=, ~=, *=, $= etc is very powerful.

Link to comment
Share on other sites

  • 0

Look for any other optional indicators you can use.

  • Can you apply a unique class?
  • Is it contained in a unique element & can you apply any classes or indicators do that?
  • Can you apply a data attribute to the button?

If you can apply a data attribute to the button, then that's personally the option I would recommend. You can then initiate this using jQuery relatively simply as noted above.

Link to comment
Share on other sites

  • 0

I like to use a unique class as mentioned above.  It doesn't even need to be a real class.

Add a unique class name like this to your button:

<input id="mybutton" type="button" value="click me" class="_myuniqueclassname" />

 

Add the jquery click event like so:

$("input._myuniqueclassname").on("click", function() {
    //do something here
});
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.