1

How to surround element with div tag in dojo?

<button>Testing</button>
:
<div>
<button>Testing</button>
</div>


<div>Testing <span>something</span></div>
:
<div>
<div>Testing <span>something</span></div>
</div>
Martin Braun
  • 10,906
  • 9
  • 64
  • 105
Dyapa Srikanth
  • 1,231
  • 2
  • 22
  • 60

5 Answers5

2

Finally I found answer

Surrounding

var node = domConstruct.create("div");
dojo.addClass(node,"container");
var refNode = dom.byId("refNode");
var tagName = refNode.tagName.toLowerCase();
node.innerHTML="<"+tagName+">"+refNode.innerHTML+"</"+tagName+">";
domConstruct.place(node, refNode,"before");
domConstruct.destroy(refNode);
Dyapa Srikanth
  • 1,231
  • 2
  • 22
  • 60
1

Its pretty simple

 require(["dojo/dom-construct"], function(domConstruct){
      var n = domConstruct.create("div", { innerHTML: "Testing <span>something</span>" });
    });

read all about it here

varun
  • 4,522
  • 33
  • 28
  • It just creates new div with some innerHTML. It won't replaces existing one. And innerHTML for button is Testing only, what about tag name( – Dyapa Srikanth May 17 '13 at 10:54
  • well you need to grab the innerhtml first in that case, then append the new markup , so lets say that you have an existing div with some markup inside, first you will copy the existing markup in a variable then replace all content of the parent with the new markup bust as an innerHTML of a div, this will wrap it inside a div as you requested. – varun May 17 '13 at 10:56
1

How about this :

var refNode = dom.byId("refNode");
// make the new div, with the correct class, directly after the node to be wrapped
var node = domConstruct.create("div", {"class":"container"}, refNode, "after");
// move the refNode inside our wrapping node
domContruct.place(refNode, node);
Frances McMullin
  • 5,516
  • 2
  • 18
  • 19
1

A quick and dirty approach looks like this:

element.outerHTML = '<div>' + element.outerHTML + '</div>';

No need for any libraries. Note, this will create a new object under the hood, so you have to retrieve element again to get the surrounding element, in case you need it afterwards.

Overall, it's handy, because you do not have to remove the old element and insert the new one.

I also came up with a similar approach to replace the tag name and preserve attributes, which might be interesting for one or another.

Martin Braun
  • 10,906
  • 9
  • 64
  • 105
0

I don't know how it was in 2013, but these days, dojo's NodeList-manipulate functionality allows you to do it quite easily.

Given:

<b>one</b>
<b>two</b>

Use:

require(["dojo/query", "dojo/NodeList-manipulate"], function(query){
  query("b").wrap("<div><span></span></div>");
});

Output:

<div><span><b>one</b></span></div>
<div><span><b>two</b></span></div>

This example is take from the documentation here.

Wolfie Inu
  • 101
  • 1