JavaScript Unwrapped Wrap

I have non-static content on my web page, and I need all the expanded plain text to be wrapped inside the class binding element, however I need to keep the placement of this text.

I searched on this site and found questions such as these that ask the same question, except that the text is always at the beginning or at the end and the answers always add / add content back to <div>.

To make this question even more complex, there are scenarios in which the content will only be expanded in plain text, and I also need to wrap it.

My HTML:

<div>
  <a>1</a>
  <a>2</a>
  3
  <a>4</a>
</div>

Sometimes:

<div>
  1
</div>

I tried all the answers on the this page , but they all change the order of the text.

Any ideas?

+4
1

:

$('div').contents().filter(function() {
    return this.nodeType === 3;
}).wrap('<a class="awesomeClass"></a>');

DEMO

.contents() , .

.filter , . :
DOM node nodeType, ( ). . 1, 3. .filter , false.

.

.

HTML

<div>
  1
</div>

node, node. node (), , . . ( - , ¬ - ):

<div>¬
⋅⋅1¬
</div>

node ¬⋅⋅1¬.

node, :

$('div').contents().filter(function() {
    return this.nodeType === 3;
}).each(function() {
    this.nodeValue = $.trim(this.nodeValue);
}).wrap('<a class="awesomeClass"></a>');

DEMO

+12

All Articles