Reputation: 1621
I have the following tag in an html page:
<li class="slogan">888-888-8888</li>
I am trying to change it for it to look like this:
<li class="phone">
<i class="icon-phone"></i>
<a href="tel:888-888-8888">888-888-8888</a>
</li>
I used the following code that i found to change the class name which works perfect, but i can't figure out how to change the contents to match what i want.
var els = [].slice.apply(document.getElementsByClassName("slogan"));
for (var i = 0; i < els.length; i++) {
els[i].className = els[i].className.replace(/ *\bslogan\b/g, "phone");
}
Upvotes: 0
Views: 72
Reputation: 1919
Since you are already cycling through the tags and have the item identified els[i], all you have to do is write to the innerHTML of that item.
var els = [].slice.apply(document.getElementsByClassName("slogan"));
for (var i = 0; i < els.length; i++) {
els[i].className = els[i].className.replace(/ *\bslogan\b/g, "phone");
els[i].innerHTML = "NEW CONTENTS";
}
Upvotes: 0
Reputation: 61055
$('li.slogan').toggleClass('slogan phone')
.wrapInner(function() {
return '<a href="tel:' + $(this).text() + '"></a>'
})
.prepend('<i class="icon-phone"></i>');
Upvotes: 3
Reputation: 1
Try utilizing els[i].textContent
to set href
, text of a
element , .innerHTML
var els = [].slice.apply(document.getElementsByClassName("slogan"));
for (var i = 0; i < els.length; i++) {
var text = els[i].textContent;
els[i].className = els[i].className.replace(/ *\bslogan\b/g, "phone");
els[i].innerHTML = "<i class=icon-phone></i>"
+ "<a href=tel:" + text + ">" + text + "</a>";
}
<ul>
<li class="slogan">888-888-8888</li>
</ul>
Upvotes: 0
Reputation: 11297
$('.slogan').each(function(){
$(this).removeClass("slogan").addClass("phone"); // remove class and add .phone
$(this).html('<i class="icon-phone"></i><a href="tel:'+$(this).text()+'">'+$(this).text()+'</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="slogan">888-888-8888</li>
<li class="slogan">888-888-3626</li>
<li class="slogan">888-888-2551</li>
Upvotes: 0
Reputation: 207881
You can use jQuery's .replaceWith()
function to do what you're after:
$('li.slogan').replaceWith(function() {
return '<li class="phone"><i class="icon-phone"></i><a href="tel:' + $(this).text() + '">' + $(this).text() + '</a></li>'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="slogan">888-888-8888</li>
Upvotes: 0