最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Change CSS on HTML button click? - Stack Overflow

matteradmin9PV0评论

I want to modify the CSS of a page (hide elements of a certain class, "class") when a user clicks a button. I can't seem to find the correct JavaScript for getting this button to trigger the style change. I would prefer to avoid jQuery in my solution.

HTML:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <script type="text/javascript" src="content.js"></script>
</head>

<body>
    <p>hide "class"</p>
    <button type="button" onclick="hide_class()">hide class</button>
</body>

</html>

JavaScript:

function hide_class() {

    document.addEventListener("DOMSubtreeModified", function (event) {
        if (document.getElementsByClassName(".class")) {
            var x = document.querySelectorAll(".class");
            var i;
            for (i = 0; i < x.length; i++) {
                x[i].style.visibility = "hidden";
            }
        }
    });
}

Edit: Here is my manifest.json and background.js

Manifest.json (does not reference content.js):

{
"manifest_version": 2,

"name": "my extension",
"description": "it doesnt work",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
 },

"permissions": [
"declarativeContent"
 ],

"page_action": {
    "default_popup": "popup.html"
    },  

 "icons" : { "16": "16.png",
          "48": "48.png",
          "128": "128.png" },

  }

Background.js:

chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
  {
    conditions: [
      new chrome.declarativeContent.PageStateMatcher({
        pageUrl: { urlContains: 'g' }, //url contains g
      })
    ],
    actions: [ new chrome.declarativeContent.ShowPageAction() ]
  }
 ]);
 });
 });

I want to modify the CSS of a page (hide elements of a certain class, "class") when a user clicks a button. I can't seem to find the correct JavaScript for getting this button to trigger the style change. I would prefer to avoid jQuery in my solution.

HTML:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <script type="text/javascript" src="content.js"></script>
</head>

<body>
    <p>hide "class"</p>
    <button type="button" onclick="hide_class()">hide class</button>
</body>

</html>

JavaScript:

function hide_class() {

    document.addEventListener("DOMSubtreeModified", function (event) {
        if (document.getElementsByClassName(".class")) {
            var x = document.querySelectorAll(".class");
            var i;
            for (i = 0; i < x.length; i++) {
                x[i].style.visibility = "hidden";
            }
        }
    });
}

Edit: Here is my manifest.json and background.js

Manifest.json (does not reference content.js):

{
"manifest_version": 2,

"name": "my extension",
"description": "it doesnt work",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
 },

"permissions": [
"declarativeContent"
 ],

"page_action": {
    "default_popup": "popup.html"
    },  

 "icons" : { "16": "16.png",
          "48": "48.png",
          "128": "128.png" },

  }

Background.js:

chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
  {
    conditions: [
      new chrome.declarativeContent.PageStateMatcher({
        pageUrl: { urlContains: 'g' }, //url contains g
      })
    ],
    actions: [ new chrome.declarativeContent.ShowPageAction() ]
  }
 ]);
 });
 });
Share Improve this question edited Jan 8, 2017 at 4:41 Nat asked Jan 4, 2017 at 20:56 NatNat 671 silver badge10 bronze badges 5
  • do you want to add listener or change style? – Iłya Bursov Commented Jan 4, 2017 at 21:08
  • I want to change the style when the button is clicked, but I believe I need to implement the listener to change the style, unless someone has a better idea on how to acplish this. – Nat Commented Jan 4, 2017 at 21:12
  • listener listens to changes, it does not initiates changes – Iłya Bursov Commented Jan 4, 2017 at 21:38
  • Your "wondering" regarding your Chrome extension can not be addressed without more code (i.e. a plete minimal reproducible example that includes your manifest.json and any background script). However, your content script does have to get injected into the page somehow. There are two ways to do so, either a content_script entry in manifest.json or using chrome.tabs.executeScript() in your background script/popup. – Makyen Commented Jan 4, 2017 at 21:42
  • I was not sure if more code was necessary but I've updated it for the sake of clarity – Nat Commented Jan 4, 2017 at 22:13
Add a ment  | 

3 Answers 3

Reset to default 2

You could add an event listener to the element.

Example:

HTML

<div id="hide_me">
  I will hide if you click me
</div>

JS

document.getElementById('hide_me').addEventListener('click', function () {
  this.style.display = 'none';
});

Fiddle: https://jsfiddle/y1gc01zj/1

EDIT you could also add a css class:

CSS

.hide {
  display: none;
}

JS

document.getElementById('hide_me').addEventListener('click', function () {
    //  this.style.display = 'none';
  this.classList.add('hide')
});

Probably you're looking for this:

function sw(cl, v) {
  var a = document.getElementsByClassName(cl);
  for (var i=0; i<a.length; i++) a[i].style.visibility = v;
}
<p class="c1">c1</p>
<p class="c2">c2</p>
<p class="c1">c1</p>

<button onclick="sw('c1', '');">show c1</button>
<button onclick="sw('c1', 'hidden');">hide c1</button>

<button onclick="sw('c2', '');">show c2</button>
<button onclick="sw('c2', 'hidden');">hide c2</button>

Your issue is this typo:

in function hide_class() {

if(document.getElementsByClassName(".class")) {

should be

if(document.getElementsByClassName("class")) {

Post a comment

comment list (0)

  1. No comments so far