mondayguy
mondayguy

Reputation: 991

Select all contenteditable divs

I'm trying to select all contenteditable div and change some of this functions:

$("div[contenteditable='true']").each(function() {
   console.log($(this).id);
   $(this).onblur="onDivBlur(this)" ;
   $(this).onmouseup="saveSelection()" ;
   $(this).onkeyup="saveSelection(this)" ;
   $(this).onfocus="restoreSelection(this)";

});

What am I doing wrong? http://jsfiddle.net/mondayguy/oc2ooLto/ Can you also please provide me example of doing the same in pure js? Thanks.

Upvotes: 2

Views: 911

Answers (6)

Vaibhav
Vaibhav

Reputation: 1477

Using your example, this should work:-

$("div[contenteditable='true']").each(function(ind,elem) {
   //$(this).onblur = 
    alert($(elem).attr('id'));
   $(elem).onblur="onDivBlur(elem)" ;
   $(elem).onmouseup="saveSelection()" ;
   $(elem).onkeyup="saveSelection(elem)" ;
   $(elem).onfocus="restoreSelection(elem)";

});

Upvotes: 1

CodeDreamer68
CodeDreamer68

Reputation: 430

$(this) is the jQuery object referring to the matching element in each iteration of the "each" loop. Therefore, it doesn't have an 'id' property per-se. It is a jQuery object. Try this to access the id attribute of the element instead:

$(this).attr("id");

Upvotes: 0

Nishanth Matha
Nishanth Matha

Reputation: 6081

try this:

$("div").each(function() {
if($(this).attr("contentEditable") == "true"){
 console.log($(this).attr("id"));
 //REST OF YOUR OTHER CODE
}
});

Upvotes: 0

winhowes
winhowes

Reputation: 8065

Try doing something like this as onblur and the other properties like id are handlers/properties attached to the element this but not the jQuery element $(this):

$("div[contenteditable='true']").each(function() {
   console.log($(this).attr("id"));
   var self = this;
   $(this).blur(function(){
       onDivBlur(self);
   })
   .mouseup(saveSelection)
   .keyup(function(){
       saveSelection(self);
   })
   .focus(function(){
      restoreSelection(self);
   });
});

Note that I used jQuery's chaining to chain all of the handlers together without calling $(this) each time. You can though add the $(this) if you want though.

EDIT: jsFiddle: http://jsfiddle.net/oc2ooLto/4/

Upvotes: 0

Vishal Wadhawan
Vishal Wadhawan

Reputation: 1085

Here is your answer:

   $("div[contenteditable='true']").each(function() {

  alert($(this).attr('id'));
 $(this).onblur="onDivBlur(this)" ;
 $(this).onmouseup="saveSelection()" ;
 $(this).onkeyup="saveSelection(this)" ;
 $(this).onfocus="restoreSelection(this)";

});

Upvotes: 0

Partha Pal
Partha Pal

Reputation: 318

use $(this).attr('id') instead of $(this).id

Upvotes: 1

Related Questions