1

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>

4 Answers 4

2

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 = "";
Sign up to request clarification or add additional context in comments.

Comments

2

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>";

Comments

1

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>')

Comments

1

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>';

1 Comment

It's just because some people are using it so much it feels more natural to write jquery than javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.