Reputation: 21
I'm trying to replace the list item "<li id="menu-item-3026">...</li>
" with this line of HTML "<li><a href="https://www.facebook.com/"><i class="icon-s-facebook"></i></a></li>
" with javascript.
Any suggestions?
Current:
<div class="menu" id="menu">
<ul id="megaUber" class="megaMenu">
<li id="menu-item-3026" class="menu-item menu-item-type-custom menu-item-object-custom ss-nav-menu-item-4 ss-nav-menu-item-depth-0 ss-nav-menu-reg">
<a target="_blank" href="https://www.facebook.com/SocialFactor"><span class="wpmega-link-title">Facebook</span>
</a>
</li>
</ul>
</div>
Desired Result:
<div class="menu" id="menu">
<ul id="megaUber" class="megaMenu">
<li><a href="https://www.facebook.com/SocialFactor"><i class="icon-s-facebook"></i></a>
</li>
</ul>
</div>
Upvotes: 1
Views: 108
Reputation: 13089
Assuming no jQuery, you've two basic options.
First, use DOM functions to create the nodes programatically.
Second - update using a simple text string, as ioums has just suggested.
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
var container = byId('megaUber');
container.innerHTML = '';
var li = newEl('li');
var a = newEl('a');
a.setAttribute('href', "https://www.facebook.com/SocialFactor");
var i = newEl('i');
i.className = "icon-s-facebook";
li.appendChild(a);
a.appendChild(i);
container.appendChild(li);
Of course, you could just do it in one go, too (can't see why it wouldn't execute faster)
var container = byId('megeUber');
container.innerHTML = "<li><a href='https://www.facebook.com/SocialFactor'><i class='icon-s-facebook'></i></a></li>";
Upvotes: 2
Reputation: 1395
Why does everyone immediately go to jQuery? Just use
document.getElementById('megaUber').innerHTML = '<li><a href="https://www.facebook.com/SocialFactor"><i class="icon-s-facebook"></i></a></li>';
Upvotes: 1
Reputation: 4798
Are you using jQuery? If so you could just do the following:
$('#menu-item-3026').replaceWith('<li><a href="https://www.facebook.com/SocialFactor"><i class="icon-s-facebook"></i></a></li>')
Upvotes: 1
Reputation: 8312
Try this with jquery:
$("#menu-item-3026")
.html("<a href=\"https://www.facebook.com/\"><i class=\"icon-s-facebook\"></i></a>")
.prop("id", "");
Without jquery:
var el = document.querySelector("#menu-item-3026");
el.innerHTML = "<a href=\"https://www.facebook.com/\"><i class=\"icon-s-facebook\"></i></a>";
el.id = "";
Upvotes: 2