Skip to content Skip to sidebar Skip to footer

If Display Is Block Change It To None With Javascript

for this code #element { display : block }
how can I write javascript code like // button on click if(element-display = block){ // cha

Solution 1:

style.backgroundColor = "red"

changeColor = function(){
  // Get the element by IDvar div = document.getElementById("square");
  
  // Get the styles applied to that elementvar style = window.getComputedStyle(div)
  
  // Compare background color using rgb valueif(style.backgroundColor == "rgb(0, 0, 255)")
    div.style.backgroundColor = "red";
}
#square{
  width: 50px;
  height: 50px;
  background-color: blue;
}
<divid="square"></div><buttononclick="changeColor()">Change Color</button>

Solution 2:

try this,

document.querySelector("button").addEventListener("click", changeDiv);
functionchangeDiv(){
	var element = document.getElementById("element1");
    element.style.display = (element.style.display == 'none') ? 'block' : 'none';
}
#element1{display:block}
<divid="element1">Sample</div><button>Click here</button>

Solution 3:

Use the .css() method on the element you want to retrieve.

var theColorIs = $('element').css("color"); //Which will return the color in RGB.if(theColorIs  == 'blue') {
      $("element").css({"color": "red"}); 
}

https://www.w3schools.com/jquery/jquery_css.asp

Solution 4:

You can try this

$(document).ready(function() {
    $('.btn').on('click', function() {
        var textElement = $('.txt').get(0);
        var currentColor = textElement.style.color;
    
        if (currentColor === "blue") {
            textElement.style.color = "red";
        } else {
            textElement.style.color = "blue";
        }
    });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><pclass="txt"style="color:blue;">This is my text!</p><buttonclass="btn">Change color</button>

Solution 5:

Assuming you have a way to select the text that you want to check, and that all the text is in one element, you can use window.getComputedStyle to determine what color the element is using. You can then use an if statement to check if it's the color you're targeting and then to assign the element a different color. The following example should work in Chrome; I don't know if other browsers would return rgb(0, 0, 255) exactly, but, once you've checked what they do return, expanding the if statements to accept those strings should be fairly trivial.

document.querySelector('button').addEventListener('click', ()=> {
  let p = document.querySelector('.blue-text');
  pStyle = window.getComputedStyle(p);
  console.log(pStyle.color)
  if (pStyle.color === "rgb(0, 0, 255)") {
    p.style.color = "red";
  }
})
.blue-text {
  color: blue;
}
<pclass="blue-text">I'm some text</p><button>Change Text Color</button>

Post a Comment for "If Display Is Block Change It To None With Javascript"