Replace Text with Image - JavaScript (getElementsByClass)
I have a span:
<span class="attr attr-value">Brand Name</span>
And I wa开发者_运维问答nt to replace that text with an image, based on the text
Here is what I have:
<script type="text/javascript">
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
var filename = oldHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
var newHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
document.getElementsByClass('attr-value').innerHTML = newHTML;
</script>
What am I doing wrong here?
This line is an issue:
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
document.getElementsByClass
should be document.getElementsByClassName
, and it returns a NodeList
, which doesn't have an innerHTML
property. You'd want to loop through the NodeList
to look at the innerHTML
of each element.
Something like this (live example):
<script type="text/javascript">
(function() {
var list, index, element, filename;
list = document.getElementsByClassName('attr-value');
for (index = 0; index < list.length; ++index) {
element = list[index];
filename = element.innerHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
element.innerHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
}
})();
</script>
Changes:
- Put the whole thing in an anonymous function and immediately execute that function, to avoid creating global symbols.
- Use the correct
getElementsByClassName
- Loop through them
- Operate on the
innerHTML
of each element.
Notes:
- IE doesn't have
getElementsByClassName
, so you'll want to be sure you're loading a script that provides it on IE. That's not provided in the live example above, use Firefox, Chrome, or Opera. (Just search for "getElementsByClassName for IE" and you'll find several implementations to choose from.) - The above
script
tag will need to be placed after all of the elements you want to process in the HTML file.
class="attr attr-value"
and you're calling
document.getElementsByClass('attr-value').innerHTML
document.getElementsByClassName()
;
It should be, (e.g)
document.getElementsByClassName('attr-value')[0];
精彩评论