Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Text Nodes in a Single Element?

Could someone look at the following screenshot for me and explain the following:

Image showing weird behavior

  1. What is going on?
  2. How can I programmatically detect it?
  3. How can I programmatically fix / get rid of it?

I believe what's happening is I have multiple text nodes in a single pre element... I feel like I read on MDN many years ago that such a thing is possible, but I've never encountered anything like it before now.

jQuery doesn't reveal anything unusual about it via text() or html() (I attempt both in the console as seen in the screenshot)... it simply shows the content of all the text nodes consolidated into a single node.

Not shown is that when I attempt to manually fix this in the console, by doing:

$('pre').text($('pre').text())

Instead of replacing all the text nodes with a single text node with the content of all 3 merged into one, it only replaces the content of the first text node with the content of all 3.

All of this is really confusing me and I can't find any documentation on any of this, so I'd really appreciate it if someone could answer my questions above.

Oh, because I know someone will ask how I did this, the answer is I'm not quite sure what I did. It has something to do with the circular loop between the html and the js of my meteor project, I think:

In my html I have this:

<pre class="editable" contentEditable="true">{{text}}</pre>

And in my javascript I have this:

"input pre": function (event) {
    var newText = $(event.target).text();
    Ideas.update(this._id, {$set: {text: newText}});
}

So meteor is automatically checking for changes to text in my database and putting the latest copy into my pre. It also sees when the user edits the pre and edits the text in the database. Something about doing this somehow, sometimes yields what you see in the picture above (other times it yields other strange behaviors.)

like image 912
ArtOfWarfare Avatar asked Mar 25 '15 00:03

ArtOfWarfare


1 Answers

  1. What is going on?

There are multiple text nodes in the pre element.

  1. How can I programmatically detect it?

$('pre').contents() will return a list of children of the element, including text nodes. In my case, I'll only ever have text nodes so simply checking if the list has a length greater than 1 will work. If I weren't able to make that assumption, I would have to iterate over the returned list and see if any two consecutive nodes were text nodes. See the documentation from jQuery.

  1. How can I programmatically fix / get rid of it?

$('pre')[0].normalize() fixes it. See the documentation on normalize from MDN.

like image 58
ArtOfWarfare Avatar answered Oct 20 '22 17:10

ArtOfWarfare