HTML5 contentEditable with jQuery

35,852

Solution 1

$('#container *').attr('contenteditable','true');

* means "all element types", and is analogous to a,div,span,ul,etc...

Like most other jQuery functions, attr applies the same operation to every element captured by the selector.

Solution 2

$("#container *").attr("contentEditable", true)

Just a guess. Away from workstation.

Solution 3

I get the impression you're misunderstanding the problem in two places:

  1. jQuery creates "query" objects which provide a shorthand for manipulating sets of DOM elements. Your example code sets contentEditable on the query, not what it matches. You want jQuery's shorthand for "set an attribute on all matching elements", which is $('whatever').attr('contentEditable','true');

  2. I'm not sure you understand contentEditable properly. You're supposed to set it on the top-level container for each editable region and its effects apply to everything within. In my experience, if setting contentEditable on#container or something like #container div.post really isn't good enough, then you've got bigger problems.

Share:
35,852
David
Author by

David

Updated on July 09, 2022

Comments

  • David
    David almost 2 years

    I have some elements that need to have the text inside editable, for this I am using the HTML 5 attribute contentEditable. I can't seem to do use jQuery for this using multiple selectors. What I want to do is have every tag inside a container div be editable. Here's an example of what it would look like if it worked with jQuery:

    $("#container <all tags here>").contentEditable = "true";
    

    I dont know how to make it select all tags but you get the point.

    So all span, div, tables, bold, etc should be editable individually

  • Tim Down
    Tim Down about 11 years
    How about $('#container *').prop("contentEditable", "true")?
  • Tim Down
    Tim Down almost 11 years
    @DaveJarvis: The attribute is contenteditable, not contentEditable. If this doesn't work in some versions of IE, it's because older IE's setAttribute() implementation is broken, so I would advise using the contentEditable property instead. This is generally a good idea for almost all attributes. So, I'd recommend $('#container *').prop('contentEditable', 'true')
  • xtempore
    xtempore over 7 years
    contenteditable automatically applies to all the elements below it, so all you really need is $('#container').attr('contenteditable','true');