document.getElementById(...).style.display is blank [duplicate] - javascript

This question already has answers here:
How to retrieve the display property of a DOM element?
(4 answers)
Closed 6 years ago.
function test( id )
{
alert( document.getElementById( id ).style.display );
}
What exactly does getElementById.style.display return? Is it an object, or a value? The alert shows nothing at all. I'm not using pure numbers for the id and it is unique.

DOM methods like document.getElementById() create objects which point to- and contains certain details about- a specified HTMLElement or set of elements.
Unfortunately the .style property only knows about the style properties set using that same feature. In the example below, clicking what color? will not work until you have clicked change color.
<html>
<head>
<script>
function whatColor() {
var d = document.getElementById( 'ddd' );
alert( d.style.backgroundColor );
}
function changeColor() {
var d = document.getElementById( 'ddd' );
d.style.backgroundColor='orange';
}
</script>
<style>
#ddd {
background-color:gray;
}
</style>
</head>
<body>
<input type="button" onclick="whatColor();" value="what color?" />
<input type="button" onclick="changeColor();" value="change color" />
<div id="ddd"> </div>
</body>
</html>
I recommend reading PKK's great page on getComputedStyle and currentStyle (IE, of course is different) http://www.quirksmode.org/dom/getstyles.html
At the end of the tutorial, there is a very decent function for your purposes, although frameworks such as jQuery do provide very convenient & powerful functions for styling page elements: http://api.jquery.com/css/

it displays the value that was dynamically set. if you want to find the current value you need the computed value. the same question was asked, check my answer here
Stackoverflow

Actually it is possible using window.getComputedStyle(element[, pseudoElt]).
The method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

Your snippet will only show a value for style.display if it has actually been set, it will not necessarily show default values.

Related

Changing input type="number" - value changes, but not the front-end number [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

Access Global data-* attributes in javascript [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(17 answers)
Closed 3 years ago.
Im trying to write a little filter script for a ajax-table and im trying to open a overlay when someone clicks on the element:
<div class="at-filter" data-filter-val="{some_value}" data-filter-type="{some_type}">
...
</div>
How do i access the data-filter-type and value via javascript/jquery? Cant find anything at all via google.
Something like this is what im looking for:
this.table.find( '.at-filter' ).each(
function(index, element) {
var type=$(element).data-filter-type();
var val=$(element).data-filter-val();
self.data.filter[type] = {};
$(element).bind('click', {self:self, val:val, type:type}, type.openContextMenu);
}
)
edit: Mistakes were made!
To get attrbiute value use jquery attr() or in plain JavaScript getAttribute
But
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
Or
In plain JavaScript setAttribute
console.log($('.me').attr('data-attribute'));
console.log($('.me').attr('data-second-attr'));
$('.me').each(function() {
console.log(this.getAttribute('data-attribute'));
console.log(this.getAttribute('data-second-attr'));
this.setAttribute('data-second-attr', 'foo-bar');
console.log('after change', this.getAttribute('data-second-attr'));
})
$('.me').prop('data-attribute', 'baz')
console.log('after change', $('.me').prop('data-attribute'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="me" data-attribute="foo" data-second-attr="bar">yo</div>
You use attr:
var type = $(element).attr("data-filter-type");
You could also use data:
var type = $(element).data("filter-type"); // Read the note below, though
... but it isn't necessary or really appropriate if all you want to do is access the values of those attributes. Contrary to popular belief, data is not an accessor for data-* attributes. (It's both more and less than that.)

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

Cannot get element by id or className

I have an iframe that contains several div and other elements. I would like set focus to one of the textbox out of several textboxes.
I used:
a = iFrameObj.contentWindow.document.getElementById('myTxtBox');
But here, a is null;
I am able to get access to the textbox object using following code;
var myTextBox = iFrameObj.contentWindow.document.getElementsByTagName('input')[52];
But I would like to use more generic method to obtain object rather than hardcoding the index.
Since this textbox has unique class name, I tried following code:
var myTextBox = iFrameObj.contentWindow.document.getElementsByClassName('rgtxt')[0];
but i error:
"Object does not support this property or method"
HTML for my textbox is:
<input name="myTxtBox" type="text" class="rgtxt" id="myTxtBox" value="hello" style="display:block;color:Black;background-color:rgb(240, 241, 241);" readonly="readonly" />
Can somebody help what is the difference between these two methods in iFrame ?
try this
$("#youriFrameID").contents().find("input.rgtxt").focus();
using jquery...
Check this
$("input[id$='myTxtBox']").val()
The getElementsByClassName method is only available on IE9+, so the error message is correct (although not that clear), there is no such method on IE8.
You can read more about it here: http://msdn.microsoft.com/en-us/library/ie/ff975198(v=vs.85).aspx

How to replace the `no-js` class name by `js` on all elements? [duplicate]

This question already has answers here:
How to change all classname elements of specific classname
(2 answers)
How can I change an element's class with JavaScript?
(33 answers)
Closed 4 years ago.
What I’m trying to do is to get the elements with the class name no-js and replace it with js.
I have no idea how to do this.
I tried Googling around but couldn’t find anything, so does anyone know how to do this?
My goal is to have a menu show a drop-down navigation when clicked, but if JavaScript is disabled I want it to show on hover with CSS (I’ve already done that).
I’ve put my code on JSFiddle.
You need to iterate the returned elements and replace that portion of the class name on each one:
var els = [].slice.apply(document.getElementsByClassName("no-js"));
for (var i = 0; i < els.length; i++) {
els[i].className = els[i].className.replace(/ *\bno-js\b/g, "js");
}
Note that getElementsByClassName returns a "live list", which is why it's necessary to first make a copy of the return value (using [].slice) and iterate that list instead).
by javascript you can change the class name using
document.getElementById('elementid').className = 'classname'
if you want to add a new class by javascript use
document.getElementById('elementid').className += ' classname'
if you want to replace class name with other things use strings replace function
document.getElementById('elementid').className = document.getElementById('elementid').className.replace(your replace code)
look like a question, but seems to be the preferred way of doing it...
(function(html){html.className =
html.className.replace(/\bno-js\b/,'js')})(document.documentElement);
Example:
<!DOCTYPE html>
<html lang="en-US" class="no-js">
<head itemscope itemtype="http://schema.org/WebSite">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>
<title>Example Site| My Site Description</title>
Notice the location of this early on the document head... This ensures that it get's added immediately. This is much faster approach than a jquery alternative. I believe this is how modernizr does it.
Doesn't the name of the getElementsByClassName method give you a hint that it should return not a single element but multiple elements? Because there can be many elements with the same class in the document. Read the docs more carefully.
If you're familiar with CSS, there is document.querySelectorAll method, which retrieves elements via CSS selectors.
var plusLinks = document.querySelectorAll('a.no-js')
Then you can access individual links by their numeric index:
var firstLink = plusLinks[0]
As for the class attribute (and it is class attribute, not no-js attribute), you shouldn't remove it, but set it to a new value.
firstLink.setAttribute('class', 'js')
Or:
firstLink.className = 'js'
Since you want to remove the hover effect, and the body element already has no-js class on it, you can replace the class once for the whole page:
document.body.className = 'js'
Step 1 - get element by it's unique ID-
Element = Document.GetElementByID("whatever");
Step 2- remove the attribute class-
Element.RemoveAttribute("class");
Step 3 - create attribute class -
var attribute = document.createAttribute("class");
attribute.nodeValue = "someclassnamehere"
Element.setAttributeNode(attribute);
In Javascript you can do this by following :
document.getElementById('id').add('class');
document.getElementById('id').remove('class');

Categories