Button to close cells

I want to have a button that closes cells with a specific tag.
The following code does what I want:

SetOptions[#, CellOpen -> False] & /@ Cells[CellStyle -> “Section” , CellTags -> “A” ]

But when I try to make a Button (or Buttonbar) like

Button[“B”,
SetOptions[#, CellOpen -> False] & /@ Cells[CellStyle -> “Section” , CellTags -> “A” ]
]

nothing happens when I click the Button.

What am I missing?

=================

=================

1 Answer
1

=================

TL;DR

Tell the button where to search, with, e.g. ButtonNotebook:

Button[“B”,
SetOptions[#, CellOpen -> True] & /@
Cells[ButtonNotebook[], CellStyle -> “Section”, CellTags -> “A”]
]

You can always check with Print and friends, what is going on,

Button[“B”, Print@Cells[CellStyle -> “Section”, CellTags -> “A”]]

so clicking this reveals {} that no cell is found. Documentation says it should search in a current notebook, (which is not so precise) but a problem is that by default a Button is Method->”Preemptive” and it seems that Cells[] are lost, it can be confirmed with:

Dynamic@Cells[]

but I don’t know what’s the reason behind that because Dynamic @ EvaluationNotebook[] works well.