Remove Text From Multiple Spans Having Same Id
Solution 1:
IDs are unique, Classes are repeatable
The purpose of an id
in HTML is to identify a unique element on the page. If you want to apply similar styles or use similar scripts on multiple elements, use a class
instead:
<spanclass="myClass">data1</span><spanclass="myClass">data2</span><spanclass="myClass">data3</span><spanclass="myClass">data4</span><spanclass="myClass">data5</span><inputtype="button"id="clearbutton"value="Clear Data">
Now let's remove the text
Now, you can select all of these elements and set their text to anything you want. This example uses jQuery, which I recommend because older versions of IE don't support getElementsByClassName
:
$('#clearbutton').click(function() {
$('.myClass').text('');
});
Link to Working Demo | Link to jQuery
Or in Vanilla JS
If you're not worried about supporting IE, you can do this with vanilla JavaScript:
functionclearSpans() {
var spans = document.getElementsByClassName("myClass");
for(var i=0; i < spans.length; i++) ele[i].innerHTML='';
}
Note: You can add getElementsByClassName
to IE
I wouldn't recommend doing this because it's simpler and more widely accepted to just use jQuery, but there have been attempts to support older IEs for this function:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = newRegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
Solution 2:
Dont give same ID to more than one one tag, use class instead
<spanclass ="myId">data1</span><spanclass ="myId">data2</span><spanclass ="myId">data3</span><spanclass ="myId">data4</span><spanclass ="myId">data5</span>
call this function to clear
functionclearAll()
{
var ele= document.getElementsByClassName("myId");
for(var i=0;i<ele.length;i++)
{
ele[i].innerHTML='';
}
}
Solution 3:
You are using a DOM method that relies to the DOM of ID, that is, per DOM, there can only be one element with the same ID.
However, you do not use the id attribute that way in your HTML, so instead you are looking for the selector to query all elements with the id myId, you perhaps know it from CSS:
document.querySelectorAll("#myId").innerHTML = '';
This does not work out of the box, you also need to add the innerHTML
setter to the NodeList
prototype, but that is easy:
Object.defineProperty(NodeList.prototype, "innerHTML", {
set: function (html) {
for (var i = 0; i < this.length; ++i) {
this[i].innerHTML = html;
}
}
});
You find the online demo here: http://jsfiddle.net/Pj4HD/
Post a Comment for "Remove Text From Multiple Spans Having Same Id"