Why CSS isn't working on innerHTML in Pure JavaScript? [duplicate] - javascript

<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
google
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alert display nothing other than a empty string, which I thought should be none and block.
However after the intensionally display setting, the third alert finally alert none.
But Why? How could I retrieve the display property correctly?
Thanks.

The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.
I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.

You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle() whereas the nearest equivalent in IE is the element's currentStyle property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}

I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.

If you can use jQuery, there is a method called .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible') ...
This would return false if display attribute is set to None.

Related

How to get an html element's color? [duplicate]

<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
google
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alert display nothing other than a empty string, which I thought should be none and block.
However after the intensionally display setting, the third alert finally alert none.
But Why? How could I retrieve the display property correctly?
Thanks.
The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.
I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle() whereas the nearest equivalent in IE is the element's currentStyle property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.
If you can use jQuery, there is a method called .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible') ...
This would return false if display attribute is set to None.

How can i hide class contain specific value?

How can i hide a the text under class named amount using javascript or php?
<span class="amount">$0.00</span>
I tried the following but no luck
<script language="javascript">
$(".amount:has(a:contains('$0.00'))").hide();
</script>
Assuming jQuery based on code in original question.
Your original script was close. All you really need is:
$('.amount:contains($0.00)').hide()
Documentation: https://api.jquery.com/contains-selector/
Bonus
If you can't use jQuery, here's how to do it the old fashioned way.
Array.prototype.forEach.call(document.getElementsByClassName('amount'), function (e) {
if (e.innerText == '$0.00') {
e.style.display = 'none';
}
})
Setting styles is JavaScript isn't too clean, so the better thing to do would be to set a class, with corresponding CSS to hide elements matching that class. For example e.classList.add('hidden'); and .hidden { display: none; }
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach (IE 9+)
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList (IE 10+)
Try something like:
<script>
// Assign object
var AmtObj = $(".amount");
// Get contents
var Amount = AmtObj.html();
// If equals '$0.00', hide
if(Amount == '$0.00') {
AmtObj.hide();
}
</script>
try with this code:
var item = $(".amount");
if(item.html() === "$0.00"){
item.hide();
}
Its a lot of trouble for what you want especially if you wanna extract the numbers without the formatting.
If you control the data add a data-value to your attribute and put the raw number their such as <span class="amount" data-value='0.00'>$0.00</span> and then select it and hide it.
$(document).ready(function(){
$(".amount:contains('$0.00')").hide();
});

How to get `background-color` property value in Javascript? [duplicate]

This question already has answers here:
Get the computed style and omit defaults
(7 answers)
Closed 8 years ago.
fiddle
The following code alerts empty string:
HTML:
<div id="test">test</div>
CSS:
#test{
background-color: #f00;
}
SCRIPT:
alert(document.getElementById('test').style.backgroundColor)
But if I set bgcolor in javascript then it would alert the bgcolor value:
document.getElementById('test').style.backgroundColor='#ff0';
alert(document.getElementById('test').style.backgroundColor) // rgb(255,255,0)
So, how can I get the bgcolor value without setting it in js that is defined in stylesheet?
Note that I don't want to get a value at all if it comes from the user agent's stylesheet rather than mine.
The reason you're not seeing anything from .style is that that only gives you the styles set on the element, not ones it receives from stylesheets.
For modern browsers, you can use window.getComputedStyle to get the computed style object for the element. For IE8 (and earlier, but...), you can use .currentStyle to get much the same thing. So:
var element = document.getElementById('test');
var style;
if (window.getComputedStyle) {
style = window.getComputedStyle(element);
} else {
style = element.currentStyle;
}
if (!style) {
// ...seriously old browser...
} else {
alert(style.backgroundColor);
}
I just want to get stylesheet value.
getComputedStyle/currentStyle will give you that, but will also give you the browser's default style.
There's no simple interface to get only the value from your own stylesheets and not from the user agent's default stylesheet. You might want to look at the document.styleSheets property, which gives you access to the individual parsed stylesheets and their rules. But you'd have to handle the logic of applying those rules to the element in question, which is (of course) non-trivial.
Use this Code:
window.getComputedStyle(document.getElementById('test')).getPropertyValue("background-color")
Hope this may be useful

Javascript - getting the background color of the hovered element

I'm currently making a google chrome extension and am using this javascript to change dynamically the background color of the hovered element:
var bindEvent = function(elem ,evt,cb) {
//see if the addEventListener function exists on the element
if ( elem.addEventListener ) {
elem.addEventListener(evt,cb,false);
//if addEventListener is not present, see if this is an IE browser
} else if ( elem.attachEvent ) {
//prefix the event type with "on"
elem.attachEvent('on' + evt, function(){
/* use call to simulate addEventListener
* This will make sure the callback gets the element for "this"
* and will ensure the function's first argument is the event object
*/
cb.call(event.srcElement,event);
});
}
};
bindEvent(document,'mouseover', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
bindEvent(document,'mouseout', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
and when used with static values, like target.style.background = #FFFFFF; when the cursor hover an element and target.style.background = #00000; when the cursor leave the element, it works perfectly. However, when I try to get the value of target.style.background or even target.style.backgroundColor, I always get rgb(255,255,255), no matter what the background color of the element is.
I know how to convert rgb to hexa and how to inverse it, but if I can't get the initial value of the background, it's useless.
So, my question is: why do var foo = target.style.backgroundColor; always return rgb(255, 255, 255) and how do I get the correct value?
Additional notes: the extension will be ported to other browsers later, so a cross-browser solution would be nice if it is possible.
In my experience, target.style is only populated with inline styling. To get style including css definitions just use the getComputedStyle method. For example
//instead of this
target.style.backgroundColor
//try this
getComputedStyle(target).backgroundColor
*Note that using the getComputedStyle method returns a read-only object, and target.style should still be used to set the background color.
You can't use .style to get settings that haven't been defined using .style or style="". Most browsers implement other ways for getting at current style calculations, these are a minefield of oddities however.
Internet explorer has .currentStyle, whereas the rest tend to implement .getComputedStyle. It would be a good idea to read up on these two subjects, to see their implementation — however, as I have said retrieving style settings is a much more complicated process than it first seems.
Even jQuery's css method only returns settings that have been specifically determined on that element i.e. no inheritance.
The following could be of use however:
http://upshots.org/javascript/jquery-get-currentstylecomputedstyle
The only reliable way I know of is to associate a CSS class or ID with a colour, then extract that from an anchor in a hidden element, or simply from empty anchor tag with the class applied. Otherwise it really is about knowing what that colour is and having it already stored as a value somewhere. My HTML would be the following for this solution:
<style>
a:hover,
a#yourChosenIdName {
background-color:#00FF00;
}
</style>
<!-- -->
<script>
var el = document.getElementById('yourChosenIdName'),
getStyle = el.currentStyle ? el.currentStyle : getComputedStyle(el),
hoverBackgroundColor = getStyle.backgroundColor;
//do something with background-color
</script>

Check if element legally supports the src attribute or innerHTML

Is there a way to check whether an element can display innerHTML or $.html() (like elems that have a separate closing tag) OR is an element whose is meant to have a src attribute according to the HTML spec such as <img>? I'm looking for fast/reliable way to do this via jQuery or native JavaScript.
Edit: According to the HTML spec, elements not designed to have inner content are called void elements but there are also elements like this <iframe src=url>inner</iframe> that are totally valid.
Unfortunately, there isn't a foolproof way to do this because in Javascript, any element can have those attributes.
Also, as odd at it may seem, almost all HTML elements, including <img>, have an innerHTML attribute, even though it can't really use it!
Your best bet is to make a table that specifies what elements have what.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
</style>
</head>
<body>
<div id="anElementWithInnerHTML"></div>
<img id="anElementWithInnerSRC" />
<script>
var div = document.getElementById("anElementWithInnerHTML");
console.log(div.innerHTML); //Outputs ""
console.log(div.src); //Outputs undefined
var img = document.getElementById("anElementWithInnerSRC");
console.log(img.innerHTML); //Outputs "" (weird right?)
console.log(img.src); //Outputs ""
</script>
</body>
</html>
I suppose you could do
if (typeof element.src !== 'undefined')
if (element.innerHTML ...)
Not totally reliable since any element could add those properties (JSON).
(thanks for the typeof fix, thief)
I found the list of elements that (according to the spec) allow the src attribute:
audio, embed, iframe, img, input, script, source, track, video
So this works to check by name:
function srcAllowed(tag) {
if ( !tag ) { return false; }
var tags = ['audio','embed','iframe','img','input','script','source','track','video'];
return 0 <= $.inArray(tag.toLowerCase(), tags); // boolean
}
This works for getting the appropriate content:
function getContent(elem) {
// #param elem is a selected element like $(this)
// returns empty string if attr() and html() are both are falsey
return elem.attr('src') || elem.html();
}
And this is even safer:
function getContentSafer(elem) {
// #param elem is a selected element like $(this)
// returns empty string if attr() and html() are both are falsey
return srcAllowed(elem.prop('tagName')) ? (elem.attr('src') || elem.html()) : elem.html();
}

Categories