D3 Creating Updating Selecting Large number of ways of using the d3js library for creating linking selecting and updating visual elements e g svg or html objects on screen Few examples of iterating over objects data Different approachs enter update vs each D3 Task Add 100 span elements and place random text in each one On mouse click randomly change the text and background color for all the span elements script src https d3js org d3 v7 min js script script helpers let randRange lo hi return Math floor lo Math random hi lo let randColor return rgb randRange 0 255 randRange 0 255 randRange 0 255 let randWord return Math random 1 toString 36 substring 7 assume there are no elements on screen for let i 0 i 100 i d3 select body append span text randWord mouse click window onclick console log clicked d3 selectAll span each function dataObject warning can t use Arrow Notation let d3Element d3 select this d3Element style color randColor console log ready script Same as before but using enter and array of data script src https d3js org d3 v7 min js script script helpers let randRange lo hi return Math floor lo Math random hi lo let randColor return rgb randRange 0 255 randRange 0 255 randRange 0 255 let randWord return Math random 1 toString 36 substring 7 assume there are no elements on screen create 100 data elements instead then use enter to add them let worddata Array from new Array 100 map d return randWord d3 select body selectAll span data worddata enter append span text d return d mouse click window onclick console log clicked d3 selectAll span each function dataObject warning can t use Arrow Notation let d3Element d3 select this d3Element style color randColor console log ready script
ect this d3Element style color randColor console log ready script Same as before but using enter and array of data script src https d3js org d3 v7 min js script script helpers let randRange lo hi return Math floor lo Math random hi lo let randColor return rgb randRange 0 255 randRange 0 255 randRange 0 255 let randWord return Math random 1 toString 36 substring 7 assume there are no elements on screen create 100 data elements instead then use enter to add them let worddata Array from new Array 100 map d return randWord d3 select body selectAll span data worddata enter append span text d return d mouse click window onclick console log clicked d3 selectAll span each function dataObject warning can t use Arrow Notation let d3Element d3 select this d3Element style color randColor console log ready script