Search code examples
javascriptintellij-ideaphpstormwebstorm

Code completion for HTML DOM in JavaScript string literals in IntelliJ / PhpStorm


I am using a custom framework that shortens document.getElementById like so:

function $$(elementId){ return document.getElementById(elementId); }
    
$$("someDOMid").style.color = "#336699";

I am using JetBrains IntelliJ / PhpStorm (although this would apply to WebStorm as well I would presume).

I note that in the IDE, code completion for HTML DOM ids shows up for document.getElementId and also jQuery's $("#someId") functions.

How do I get PhpStorm to recognize my framework's wrapper as the same as the native call, and thus get those very handy DOM code completions?


Solution

  • jQuery's $("#someId")

    If you want jQuery style where you need to have # before the ID (just like in the quoted example) then it's not a problem at all. We're going to do the same thing that is used for querySelector() and querySelectorAll().

    1. Go to Settings/Preferences | Editor | Language Injections

    2. Locate js: DOM Element selectors entry.

    3. Clone it (use Duplicate icon button on it).

      NOTE: I always recommend making your own rule instead of modifying existing bundled one (you can disable original one if it's not needed). This way you can see the updates in the bundled one + reduce "why it does not work for me" situations (e.g. the pattern was updated or completely reworked to accommodate other scenarios but you cannot see that since you are using modified old pattern).

    4. Now open the cloned entry. It will have "IDE" or "Project" in the Scope column (while the original bundled entry will have "Built-in" there)

    5. Give it a new name (e.g. Custom $$) and adjust the pattern. Super easy -- just have "$$" instead of the default "querySelector", "querySelectorAll", "closest"

    6. Save and close

    7. Go back to the editor and test it.

    enter image description here
    (numbers here do not exactly correspond the steps in the list above)

    Looks OK here:

    enter image description here


    If you want to have it without the need of having # present before the ID (similar to document.getElementId)... well just add that symbol in the Prefix field -- should do the job.

    enter image description here

    Seems to work OK in my quick test:

    enter image description here