I'm working on a site with a visualization of inheritance relation.
I try to link each nodebox with specific URLs. The html of Element looks like this:
<g class="node" id="RootNode" transform="translate(0,453.125)">
I used
$('#RootNode').click(function(){//do something}
and also
document.getElementById("RootNode").onclick(){//do something}
Neither of them can find the element, nor setup the onclick function.
Have I misunderstood anything? Any information will be helpful. Thanks.
I'm working on a site with a visualization of inheritance relation.
I try to link each nodebox with specific URLs. The html of Element looks like this:
<g class="node" id="RootNode" transform="translate(0,453.125)">
I used
$('#RootNode').click(function(){//do something}
and also
document.getElementById("RootNode").onclick(){//do something}
Neither of them can find the element, nor setup the onclick function.
Have I misunderstood anything? Any information will be helpful. Thanks.
Share Improve this question edited Feb 17, 2014 at 19:06 Felix Wang asked Feb 17, 2014 at 17:01 Felix WangFelix Wang 731 gold badge2 silver badges5 bronze badges 2- Neither of those syntaxes are correct. – gen_Eric Commented Feb 17, 2014 at 17:03
- Does the #RootNode element already exist when the handler is bound? – fast Commented Feb 17, 2014 at 17:09
4 Answers
Reset to default 26Make sure your code is in DOM Ready as pointed by rocket-hazmat
.click()
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
.on()
Use event Delegation/
$(document).on("click", "#RootNode", function(){
//do something
});
Try
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
$(document).ready(function() {
$("#click").click(function(){
console.log("button clicked");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="click">Click Me</button>
You can try this one:
document.getElementById("RootNode").onclick = function() {
/* do something */
};