New to jQuery, having an issue with dynamically changing the selector.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
function addFirst(){
var fc = document.getElementById("fc").value;
$("#parent").append("<div id='firstChild" + fc + "'>My boring text.</div><a href='#' onClick='addSecond(\"firstChild" + fc +"\")'>Add Second Child</a>");
fc = (fc - 1) + 2;
document.getElementById("fc").value = fc;
}
function addSecond(){
$(***THE PARENT SELECTOR***).append("<div>Some more boring text.</div>");
}
</script>
<body>
<input type="hidden" id="fc" value="1"
<div id="parent"></div>
<a href="#" onClick=" addFirst('#parent');">Add First Child</a>
</body>
</html>
I need a selector that gets me the direct parent of an object when that parent object has been created dynamically, as indicated by my text “THE PARENT SELECTOR“.
EDIT
My solution to this, in case anyone else comes across this question, was to use .call inside the onClick event.
Located in the string of the addFirst() function:
<a href='#' onClick='addSecond.call(this,\"firstChild" + fc +"\"); return false;'>
Then, changed the addSecond() function:
$(this.parentNode).prepend("<div>BlahBlah");
It shouldn’t matter how the object was created, the selector will work the same.
As noted, this will not work unless you pass a reference to your object. You could leverage jQuery more and all of this will be much easier:
Note, that I added a class
addfirstandaddsecond. These are used to add handlers to the links automatically (or more accurately, attach handlers to the body, which trigger when divs with these classes are clicked). When they are clicked,thisis passed to the function, allowing you to find that object’s parent, etc.You could clean this code up even further, but I can’t guess how you are using it. I am guessing you want the children added somewhere different than where they are actually ending up.
Example: http://jsfiddle.net/2LjYH/
If I were to guess, I would make
#parentwrap the “Add First Child” link, like this:Example: http://jsfiddle.net/XjUzA/
This seems to work more intuitively. And if you want the second child added directly after the link, you don’t want
.parent().append()at all, you simply want to use.after():Example: http://jsfiddle.net/XjUzA/1/