Reputation: 5
I learned a lot of shortcuts in Visual Studio Code, some natives and some others from extensions, but I didn't succeed to find any "addClass" extension for HTML. I know we can add one with Emmet on a div creation, but is there a way to quickly add a class tag if the div is already written?
Upvotes: 0
Views: 5685
Reputation: 181050
I reworked an extension that I wrote Find and Transform to simply do what you want (and a lot more).
In your keybindings.json
:
{
"key": "alt+r",
"command": "findInCurrentFile",
"args": {
"find": ">",
"replace": " class=\"@\">",
"restrictFind": "once",
"cursorMoveSelect": "@"
}
}
This command will search for a >
character, replace it with " class=\"@\">"
and then move the cursor to and select the @
character (which was added in the replace just to have an easy place to select).
The cursorMoveSelect
value can be any text, not just a single character.
As you can see in the demo, you only need to place the cursor somewhere before the character you are searching for.
The replace field can take case modifiers, like \U
and regex capture groups.
The find can be restricted to the first occurrence, all occurrences on a line, in selection(s) or the entire document.
The extension can also do searches across files with all the usual vscode options.
One benefit to the extension over simply doing a find/replace yourself is that these find/replacements can be stored for later use in the settings or simply in a keybinding.
Upvotes: 1
Reputation: 28663
With the help of 2 extensions: multi-command and Select By
Define this keybinding: (choose your own keycombo)
{
"key": "alt+x", // any other key combo
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
{ "command": "moveby.regex",
"args": { "regex": ">", "properties": ["next", "start"]}},
{ "command": "editor.action.insertSnippet",
"args": { "snippet": " class=\"$1\"$0" } }
]
}
}
Place the cursor in the start tag (not before the >
) and press key combo.
I will add an option to the moveby.regex
command to allow the cursor at the right location so you can place the cursor also before the >
.
Edit
with Select By v1.5.0 you can place the cursor anywhere in the start tag.
Modify the keybinding to (checkCurrent
property)
{
"key": "alt+x", // any other key combo
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
{ "command": "moveby.regex",
"args": { "regex": ">", "properties": ["next", "start"]},
"checkCurrent": true },
{ "command": "editor.action.insertSnippet",
"args": { "snippet": " class=\"$1\"$0" } }
]
}
}
It also works with Multi Cursor.
Upvotes: 0
Reputation: 11
if you want to add a class within a div tag or any element within Visual Studio Code, you can simply type "div.className", when you press enter the div tag will appear with a class which corresponds to the div tag. The "." feature works on any element of HTML
Upvotes: 1