Cedrik Newsletter
Cedrik Newsletter

Reputation: 57

Append elements with different attributes

I am trying to add buttons to a div with the append Method using D3. Each added button should have a different onclick-attribute.

var row = 0;

function addButton () {
  row++
  d3.select("div")
    .append("button")
    .text("Add Node - Row " + row)
    .attr("onclick", "addNode(row)");
}

function addNode(row) {
  window.alert(row);
}
<script src="https://d3js.org/d3.v4.min.js"></script>


<button onclick="addButton()">Add Button</button>
<div></div>

When I run the function 'addButton' it correctly adds a button to the the div. However when I add a second button by running the function one more time the attribute of the first button gets overwritten, so that both buttons now have the the same onclick-attribute. Oddly enough it works for ".text" but not for ".attr". What do I have to do to not effect the previous added buttons?

Upvotes: 2

Views: 44

Answers (1)

Jan Wendland
Jan Wendland

Reputation: 1420

It works for text since you actually use the value of the row variable. Simply do the same thing as you've done in your call to text() and it will work as expected (note addNode(${row})):

var row = 0;

function addButton () {
  row++
  d3.select("div")
    .append("button")
    .text("Add Node - Row " + row)
    .attr("onclick", `addNode(${row})`);
}

function addNode(row) {
  window.alert(row);
}
<script src="https://d3js.org/d3.v4.min.js"></script>


<button onclick="addButton()">Add Button</button>
<div></div>

Upvotes: 1

Related Questions