How to apply CSS style to all elements with same ID using one button?

后端 未结 6 566
小蘑菇
小蘑菇 2021-01-26 06:59

My idea was to create a button to hide/show all hidden text (Hide by highlighting the text in black, show by making the background color of the text transparent). But the codes,

6条回答
  •  死守一世寂寞
    2021-01-26 07:09

    Your code is only every going to update one element, because getElementById will only ever return one element (because, as we've said, id is supposed to be unique). If you need to mark multiple elements as related use a class instead. Here is a working example using class, JavaScript:

    function change() {
        var test = document.getElementById("button1");
        var els = document.getElementsByClassName("p2");
        if (test.value == "Hide Spoiler") {
            test.value = "Open Spoiler";
            for (var i=0; i

    HTML:

    
    
    Hidden text Test for more Hidden text test again. Hidden text

    If you need it to work in browsers too old for getElementsByClassName, try using jQuery. It makes this sort of thing lots easier

提交回复
热议问题