Search code examples
javascriptjqueryeditormarkdownpagedown

Pagedown using class attribute instead of id


I use Pagedown which requires to give id of wmd-input to textarea. It is written as the following in Markdown.Editor.js:

function PanelCollection(postfix) {
    this.buttonBar = doc.getElementById("wmd-button-bar" + postfix);
    this.preview = doc.getElementById("wmd-preview" + postfix);
    this.input = doc.getElementById("wmd-input" + postfix);
};

However I need to use the editor in various places of the project with different ids of textareas. Therefore it would be nice to use class instead of id attribute. How can achieve this?


Solution

  • I have what I imagine is a similar situation to you, although I don't have a specific reliance on my ID's, so I don't mind swapping them out with JS, I have no styling applied to the ID's (I have classes for that).

    What I've literally just written for my own use will probably be of some use, in short it uses jQuery to swap out all textareas found on the page with a wmd editor by inserting the correct DOM structure and applying the correct ID's (replacing any existing textarea ID) with iteration considered.

    $('textarea').each(function(i) {
      var panel = $('<div/>', {'class': 'wmd-panel'});
    
      panel.append(
        $('<div/>', {'id': 'wmd-button-bar-' + i, 'class': 'wmd-button-bar'}),
        $(this).clone().attr('id', 'wmd-input-' + i)
      );
    
      $(this).replaceWith(panel);
    
      panel.after($('<div/>', {'id': 'wmd-preview-' + i, 'class': 'wmd-preview'}));
    
      var converter = Markdown.getSanitizingConverter();
      var editor = new Markdown.Editor(converter, '-' + i);
      editor.run();
    });