3

I want to remove a div element with a specific class attribute using Coffeescript. I couldn't find any examples about DOM manipulation with Coffeescript on the Internet. How can I do this? Also any references to doing DOM would be great.

  • I think you misunderstood what coffeescript is, it is a scripting language, not a DOM manipulation library ... Use jquery (or whatever you want) with coffeescript and you can manage to do it. – drinchev Apr 12 '12 at 16:23
  • I want to do something similar to what is done with javascript's `document`. Can't I do that with coffeescript? –  Apr 12 '12 at 16:33
  • 1
    I think I got it ... You don't have native javascript method for removing element with a specific class, e.g. if you want to remove an element by Id, with coffeeScript is like this ''' el = document.getElementById('id'); el.parentNode.removeChild el ''' – drinchev Apr 12 '12 at 16:37
  • 1
    CoffeeScript *is* Javascript. – Ricardo Tomasi Apr 12 '12 at 19:36

2 Answers2

5

CoffeeScript is a JavaScript preprocessor, there is no additional standard library. What this means is that if you want to do DOM manipulation you would do it the same way you would in JavaScript.

You can use any JavaScript library like jQuery with CoffeeScript, alternatively you can use the document variable directly:

element.parentNode.removeChild(element) for element in document.getElementsByClassName('some-class')

Or (for browsers not supporting that method)

element.parentNode.removeChild(element) for element in document.getElementsByTagName('*') when element.className = 'some-class'

Or, since those identifiers are somewhat long, use block syntax:

for element in document.getElementsByTagName('*')
    if element.className is 'some-class'
        element.parentNode.removeChild(element)

Relevant quote from CoffeeScript.org:

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa).

Lauren
  • 1,480
  • 1
  • 13
  • 36
0

@lauren's answer works for me but when I'm using chrome, I'm getting the following error: Uncaught TypeError: Cannot read property 'id' of undefined

Using the following works perfect, tested on Chrome.

$(document).on 'hidden.bs.modal', "#newProject", ->
  document.getElementById("<ID>").outerHTML=''
  delete element

From: https://stackoverflow.com/a/19298575/5452072

Community
  • 1
  • 1
Sam Gh
  • 530
  • 5
  • 10