How can I select and remove an HTML element (its tags and content) in VS Code?

268 Views Asked by At

First of all, there is an "Emmet: Remove Tag" feature, but that only removes the wrapping of particular tags. It doesn't remove the entire element including the children within.

I'm looking for the same execution which removes the children as well. Saves a few seconds for those who edit HTML a lot.

In the example below, I want to remove the whole <ul> element by using an emmet or similar command.

<!DOCTYPE html>
<html>
<head>
    <title>My Dummy HTML Snippet</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a dummy HTML snippet with nested tags.</p>
    <div>
        <h2>A Nested Section</h2>
        <p>This is a paragraph inside a div element.</p>
        <ul>
            <li>List item 1</li>
            <li>List item 2</li>
            <li>List item 3</li>
        </ul>
    </div>
    <p>Back to the main content.</p>
</body>
</html>
3

There are 3 best solutions below

1
rioV8 On BEST ANSWER
  • place the cursor on <ul> or </ul>
  • execute command: Emmet: Balance Outward
  • press Delete

If you need this a lot you can add a keybinding for the command Emmet: Balance Outward

If you place the cursor anywhere inside the <ul>...</ul> tag you can select the <ul>...</ul> tag by applying the command/keybinding multiple times.

This also works with Multi Cursor.

2
starball On

Notice: I think rioV8's answer (which was posted after mine) is better. I'm just leaving mine here if anyone's interested.

Put your caret after the > of the opening tag, then run the Expand Selection command twice (bound to shift+alt+right by default), which should expand the selection to the elements tags and content, and then press your delete or backspace key. Technically you can start your cursor in any part of the element's source markup, but you'll just have to expand the selection more times.

0
dev-ninja On

based on: @starball answer

open the keybindings.json file from the Command Palette (Ctrl+Shift+P) with the Preferences: Open Keyboard Shortcuts (JSON) command.

then add this to json file:

{
    "command": "runCommands",
    "key": "shift+alt+right", // whatever keybinding
    "args": {
        "commands": [
            "editor.action.smartSelect.expand",
            "editor.action.smartSelect.expand"
        ]
    }
}

Now by pressing Shift+Alt+Right Expand Selection runs twice and you do what you want

Note: you can edit keybind with whatever keybind you want