-6

I have multiple spans

<span id ="myId">data1</span>
<span id ="myId">data2</span>
<span id ="myId">data3</span>
<span id ="myId">data4</span>
<span id ="myId">data5</span>

I want to delete text inside all span on single button click.

I tried this on button click in javascript

document.getElementById("myId").innerHTML = "";

but it is removing text from only 1st span

vaibhav shah
  • 4,939
  • 19
  • 58
  • 96
  • Dont give same ID to more than one one tag, use class instead – Voonic Aug 29 '13 at 10:03
  • 6
    Ids are meant to be unique... – Patsy Issa Aug 29 '13 at 10:03
  • don't use same id for multiple elements. Assign a class and access using `getElementsByClassName('class')` or by using `getElementsByTagName('span')`. – Harry Aug 29 '13 at 10:04
  • You should never have same ids for many elements. Use class instead and then you can select all at once and do whatever you want – Manish Kumar Aug 29 '13 at 10:05
  • 1
    You would get all of the elements in nodeList with: document.querySelectorAll("#myId"); . But like n+1 comments - you're supposed to use classes instead of ids. – Samuli Hakoniemi Aug 29 '13 at 10:06
  • @hakre This is not a duplicate of this question, even if my answer does correlate well with that question. – Glitch Desire Aug 29 '13 at 10:37
  • @SweetieBelle: Right, I stand corrected. That duplicate only related. Infact, you can use just this: [`document.querySelectorAll("#myId").innerHTML = '';`](http://stackoverflow.com/a/18508979/367456) - I guess this comes pretty close to what the OP wants. – hakre Aug 29 '13 at 10:54
  • @hakre You could, but that doesn't solve the broken DOM. :D – Glitch Desire Aug 29 '13 at 10:56
  • DOM is not broken by that. You just query the attribute, not the ID, that simple it is. It is just an understanding problem. The attribute might have been "misused" here, however, if it is not used at all (e.g. ID myId is not required in DOM ID), you can not misuse it. And no, DOM is not broken, it's just unspecified which element has that ID, you can assign it manually to ensure that. – hakre Aug 29 '13 at 10:58

4 Answers4

9

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:

<span class="myClass">data1</span>
<span class="myClass">data2</span>
<span class="myClass">data3</span>
<span class="myClass">data4</span>
<span class="myClass">data5</span>

<input type="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:

function clearSpans() {
    var spans = document.getElementsByClassName("myClass");
    for(var i=0; i < spans.length; i++) ele[i].innerHTML='';
}

Link to Working Demo

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 = new RegExp("(?:^|\\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;
    }
}
}

Link to source

Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
2

Dont give same ID to more than one one tag, use class instead

  <span class ="myId">data1</span>
  <span class ="myId">data2</span>
  <span class ="myId">data3</span>
  <span class ="myId">data4</span>
  <span class ="myId">data5</span>

call this function to clear

function clearAll()
{
    var ele= document.getElementsByClassName("myId");
    for(var i=0;i<ele.length;i++)
    {
      ele[i].innerHTML='';
    }
}
Voonic
  • 4,667
  • 3
  • 27
  • 58
  • 1
    @vaibhav you can allocate ID's and classes to elements, but, as Shadow and others have said, ID's must be unique on the page – Jez D Aug 29 '13 at 10:12
  • @JezD: id attribute values must not be unique to query them. E.g. CSS does for a reason look for the attribute value, not the DOM ID. This is equally well possible with javascript and innerHTML as well: [`document.querySelectorAll("#myId").innerHTML = '';`](http://stackoverflow.com/a/18508979/367456) - I mean while we are hair-splitting here :) – hakre Aug 29 '13 at 11:01
1

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/

hakre
  • 193,403
  • 52
  • 435
  • 836
0
   var spans=document.getElementsByTagName("span");
   for(var i=0;i<spans.length;i++){
     if(spans[i].id=="myId"){
      spans[i].innerHTML="";
     }
   }

Although I suggest you don't keep same IDs

http://jsfiddle.net/YysRp/

  • This is a painfully inefficient way to do this. – Glitch Desire Aug 29 '13 at 10:36
  • @SweetieBelle for this yea, but there are times when one get data xmls with same ids, such code works very well for such situations, it is an option that is worth knowing :) –  Aug 29 '13 at 10:43