/    Sign up×
Community /Pin to ProfileBookmark

Adding parent to an element

how can i do that
i am traversing the whole document, when i find a particular element like <a> with id=’abc’, i want to append this into a <span> tag

forexample
<body>
….
<p><a id=’abc’…,</a></p>

should convert to
<body>
….
<p><span><a id=’abc’…,</a></span></p>

thx

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@samanyoluMay 03.2007 — 
&lt;script type="text/javascript"&gt;
function addElement(){

var el = document.getElementById('abc');
var span = document.createElement('span');
span.innerHTML = el.parentNode.innerHTML ;
el.parentNode.appendChild(span);
el.parentNode.removeChild(el.parentNode.childNodes[0]);
alert(document.body.innerHTML);
}
&lt;/script&gt;
&lt;body&gt;
&lt;button onclick ="addElement()"&gt;add element&lt;/button&gt;
&lt;p&gt;&lt;a id='abc'&gt;link 1&lt;/a&gt;&lt;/p&gt;
&lt;/body&gt;

Copy linkTweet thisAlerts:
@fshujaauthorMay 04.2007 — what if <p> tag has more than one child????
Copy linkTweet thisAlerts:
@CrazyMerlinMay 04.2007 — wtf....why are you using innerHTML?

a node is a node, if you reassign it you still have one node, you are not cloning it

if you assign via id and have a unique id, you don't need to worry about which child it is
Copy linkTweet thisAlerts:
@Orc_ScorcherMay 04.2007 —  var abc = document.getElementById("abc"), span = document.createElement("span")
span.appendChild(abc.parentNode.replaceChild(span, abc))
Copy linkTweet thisAlerts:
@UltimaterMay 04.2007 — replaceChild isn't as well supported as insertBefore.
<i>
</i>var e=document.getElementById("abc");
e.parentNode.insertBefore(document.createElement("span"),e).appendChild(e);
alert(e.parentNode.parentNode.innerHTML)

Note that the method appendChild automatically removes the element from its parent prior to appending to the new element so there is no need to call removeChild.
×

Success!

Help @fshuja spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...