How to check if HTML style attribute exists with javascript - javascript

I'm trying to find out if a specific element has an inline style attribute or not:
I'm sure there's an easy method to check this, but I can't seem to find it.
I tried multiple things already including this:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
Thank you for your help!

if(contentWrapper.getAttribute("style")){
if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
alert("Not Empty");
} else {
alert("Empty");
}
}

if(!contentWrapper.getAttribute("style"))
OR
if(contentWrapper.getAttribute("style")==null ||
contentWrapper.getAttribute("style")=="")
the above lines will work for you (anyone can be chosen).
In second solution:
first check watches if style attribute is present in the element, 2nd check ensures that style attribute is not present as an empty string e.g. <div id="contentWrapper" style="">
Complete code is given below:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
alert("Empty");
else
alert("Not Empty");
http://jsfiddle.net/mastermindw/fjuZW/ (1st Solution)
http://jsfiddle.net/mastermindw/fjuZW/1/ (2nd Solution)

I missed #plalx's comment the first time I scanned this page.
if (element.hasAttribute("style"))
{
var styleText = element.getAttribute("style")
}
On a related note, regarding styles...
//to get info about the end results of CSS
var computedStyle = element.currentStyle || getComputedStyle(element, null);
and
//to iterate over css styles from style tags or linked CSS
for i ...
document.styleSheets[i].rules ...
//great for searching with
var elements = document.querySelectorAll(rules[i].selectorText);

The style object has a length property which tells you if the element has any inline styles or not. This also avoids the problem of having the attribute style being present but empty.
// Would be 0 if no styles are applied and > 0 if there are inline styles applied
contentWrapper.style.length
// So you can check for it like this
contentWrapper.style.length === 0

To check style attribute exist or not for given Id
if(document.getElementById("idname").hasAttribute("style")){
alert("Style attribute found");
}else{
alert("Style attribute not found");
}

Related

jQuery .insertAfter only once with a class selector

I have the following code that is working correctly to insert a success span after an input field when a correct value is entered. But my problem is that it adds the span every time I leave the field. From question Jquery insertAfter only once if element exist I know that I could set the ID of the span when created and check the length each time the event fires to see if it already exists. But am not sure how to do that when using a class to select the fields.
Any help with class selectors would be helpful.
$(".systemFieldName").blur(function(){
var val = $(this).val();
var exists = $.inArray(val,allFields);
if (val!="" && exists>=0){
$("<span class='label label-success'>Valid</span>").insertAfter(this).one();
}
});
This should help.
allFields=["121",'test'];
$(".systemFieldName").blur(function(){
var val = $(this).val();
var exists = $.inArray(val,allFields);
//See if the next element is a span with class label.
var nextEl=$(this).next(); //next element
var add=true; //add by default
if(nextEl.hasClass('label-success')) add=false; //don't add.
if (val!="" && exists>=0 && add){ //only insert if all conditions are true.
$("<span class='label label-success'>Valid</span>").insertAfter(this).one();
}else if((val == "" || exists < 0) && !add) { // The !add means there is already the Valid span, we can safely remove nextEl, if the value changes.
nextEl.remove();
}
});
https://jsfiddle.net/ym66f48p/2/
This checks to make sure the next element is a span, it also includes a remove function that if the value is altered later on, it will remove the valid span, but ONLY if the next element is already a valid span.
use 121 or test as your testing in the jsFiddle.
Try this fiddle: https://jsfiddle.net/8jpc74z8/
All I am doing here is to check whether there is any sibling to the systemFieldName already added. If not, then add.
if($(".systemFieldName +.label-success").length === 0){

check if class does not exist on any of data- items

I have a list of div elements with a data-windows attribute:
I basically want to check if any of these are not hidden (and doing something if they are all hidden)
I'm looping through them like so, this works but I'm wondering if there's a more efficient way:
$("[data-windows]").each(function () {
if (!$(this).hasClass('hidden')) {
isSomethingShown = true;
return false;
}
});
You can use :visible pseudo selector :
if($("[data-windows]:visible").length){
//Atleast 1 is visible
}else{
//All hiden
}
or
var isSomethingShown = !!$("[data-windows]:visible").length; // Bang!Bang! [!!] convert into a boolean
Of course, if you want to explicitly check the class, both selector can be change to (and maybe should be for faster performance) $("[data-windows].hidden")
how bout this oneliner:
return $("[data-windows].hidden").length == 0 ? false : true;

Check if div only contains inline elements

I am trying to run a function that executes if a div only contains inline elements
I am not sure how to go about this short of having to list out every single block element and checking that the div doesn't contain that.
$(this).children().each(function(){
if(this.nodeName.toLowerCase() == 'p' || this.nodeName.toLowerCase() == 'h1' etc...){
check = true; //it contains block element so it is not only inline elements
return false;
}
});
Is there a better way?
Edit
To help clarify, I have a content editable div and the problem is that the user can delete all the block elements out of the div. I need to check this and add a block element to the div.
Check to see if those elements are actually block-level, as CSS can change their behavior completely:
var has_inline = $('#parent').children().filter(function() {
return $(this).css('display') !== 'block';
}).length > 0;
I'm not sure what you consider inline-block to be, so I'll just assume it behaves like an inline element for your purposes.
Demo: http://jsfiddle.net/hXckq/2/
How about has() in jQuery:
if ($(this).has("p,h1, ...")) { ... }
You could put the inline elements into a hash, then use in or hasOwnProperty:
var inline = {
"span": true,
"a": true,
...
};
if(this.nodeName.toLowerCase() in inline) {
}
Maybe try this, check if the css property of each element is indeed inline, this should work though I did not test this syntax may be incorrect:
$(this).children().each(function(){
if($(this).css('display', 'inline') == true){
return true;
}else{
return false;
}
}

Printing inline style values of an HTML element using javascript

How can i print the value of style attribute of an html element using javascript. I can get a specific style property value using document.getElementById('myId').style.property, where property is something like width, height etc.
However, how can I get the entire list of styles for an element?
document.getElementById('myId').style.cssText as a String, or document.getElementById('myId').style as an Object.
Edit:
As far as I can tell, this returns the "actual", inline style. On the element <a id='myId' style='font-size:inherit;'>, document.getElementById('myId').style.cssText should return "font-size:inherit;". If that is not what you want, try document.defaultView.getComputedStyle or document.getElementById('myId').currentStyle (the first one is all except IE, the second one is IE only). See here for more on computed vs. cascaded styles.
<div id="x" style="font-size:15px">a</div>
<script type="text/javascript">
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
// get what style rule you want
alert(getStyle(document.getElementById('x'), 'font-size'));
</script>
Oh srsly... it's as easy as
element.style.cssText
and it's cross browser
http://jsfiddle.net/4F2RQ/
This should do a dump of the object:
Here's an Example
EDIT: Its a little weird:
for (var prop in styles) {
console.log(styles[prop], styles[styles[prop]]);
}

Javascript, getting lots of elements and setting them to display none

i wish to grab a load of elements, check if their id contains 'other' or 'Other' and for those, set the display to none. This is what i have:
function Hide(div){
var list;
var i;
list = document.getElementById(div).getElementsByTagName("input")
for(i=0; i<list.length;i++){
if(list[i].id.toString().indexOf("Other") != -1 || list[i].id.toString().indexOf("other") != -1){
list[i].id.setAttribute("Style.display","none");
}
}
}
but .setAttribute... doesnt work and nor did .Style.display = "none"
Adjust the style property of the element not the string containing the id!
list[i].style.display
You can't use style.display, because 'display' is a property of the style Object.
You should use:
list[i].style.display = 'none'
Try list[i].style.display, lower case, set attribute to object itselft

Categories