简体   繁体   中英

Replacing HTML with new HTML with javascript

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>

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM