Reputation:
The specific line of code I need help with is labeled, but I've included the entire function for context. The expected output of the specified line of code should be as follows: I would like to insert the element newNode
before the element "#" + nextRank + "A"
(nextRank
is defined as a capital letter, just as rank
is). I believe the error in my code is coming from the syntax of nextRank
on the specific line, but I could be wrong. Doe's anyone know how I could fix this?
//rank is a capital letter (EX: "A")
//nodeField is a div which only parents h1's.
function addNode(rank) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var nextRank = alphabet[alphabet.indexOf(rank) + 1];
if ($('#nodeField>h1[id^="${rank}"]').length) {
var aI = alphabet.indexOf($('#nodeField>h1[id^="${rank}"]:last-child')[$('#nodeField>h1[id^="${rank}"]:last-child').length - 1]) + 1;
} else {
var aI = 0;
}
var newNode = document.createElement("h1");
newNode.innerHTML = 0;
newNode.id = rank + alphabet[aI];
if ($(`#nodeField>h1[id^="${nextRank}"]`).length > 0) {
//I need help with correcting the statement below!
document.getElementById("nodeField").insertBefore(newNode, $("#" + nextRank + "A"));
} else {
document.getElementById("nodeField").appendChild(newNode);
}
}
Upvotes: 0
Views: 225
Reputation: 3116
You mixed up jQuery and pure JS elements. There are two ways to insert a new element before.
With pure JS:
var newNode = document.createElement("h1");
newNode.innerHTML = 0;
newNode.id = "rankId";
document.getElementById("myDiv").insertBefore(newNode, document.getElementById("myInnerDiv"));
<div id="myDiv">
<div> </div>
<div id="myInnerDiv">inner div</div>
<div> </div>
</div>
In your case:
document.getElementById("nodeField").insertBefore(newNode, document.getElementById(nextRank + "A"));
With jQuery:
var newNode = document.createElement("h1");
newNode.innerHTML = 0;
newNode.id = "rankId";
$(newNode).insertBefore($("#myInnerDiv"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
<div> </div>
<div id="myInnerDiv">inner div</div>
<div> </div>
</div>
In your case:
$(newNode).insertBefore($("#" + nextRank + "A"))
Upvotes: 1