Javascript getElementById() - javascript

I'm trying to create a generic javascript function that would change attributes on events.
The way it would work is
function fooFunction(sourceElement)
{
var newName = sourceElement+'Span';
var newElement = document.getElementById(newName);
//Important line
newElement.property = "enter properties here";
}
and I'd call it with something like
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction(this.id);"/>
<span id="fooSpan" name="fooSpan">some text here</span>
So in theory, when hovering the image, it should change whatever propery I need to change on the fooSpan object. It works in Opera, but on IE it returns a null object.
Any ideas ?
The idea would be that I would have multiple images that would automatically trigger the property change on the associated text span (typically the css style).

Are you sure you're getting the ID properly in IE? Maybe the ID being passed in is null in IE (perhaps this.id isn't working?).
Try calling it like this:
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction('foo');"/>
and see if that helps. I don't see any reason why getElementById() would fail, so the only thing I can think of is that it's an ID issue.

May be this line won't work in IE. "newElement.property"
I don't know the exact reason.
You can use this instead of that line
newElement.setAttribute(property,"enter properties here");
In the mean time, i am trying to find out the reason behind the error.

My suggestion would to do something like this.
function fooFunction(sourceElement,property,propertyValue) {
var newElement = document.getElementById(sourceElement);
newElement.setAttribute(property,propertyValue);
};
And your HTML would look like:
<img src="foo.gif" id="foo" name="foo"
onmouseover="fooFunction('fooSpan','class','mouseover_span');"/>
<span id="fooSpan" name="fooSpan">some text here</span>

I'd STRONGLY urge you to consider using jQuery's built-in attr() method which integrates the function you want perfectly across browsers and is incredibly easy to use.
Using your example, if you wanted to change the "src" property for "foo", you could do it in a single line of code:
$("#foo").attr("src","images/whatever.png");
Similarly, if you wanted to change the html WITHIN "fooSpan", all you'd have to do is:
$("#fooSpan").html("something else");
You can even tie these to events that are going to give you a lot more flexibility than the onmouseover property:
$(document).ready(function(){
$("#foo").mouseover(function(){
$("#fooSpan").html("something else");
$("#foo").attr("src","images/whatever.png");
});
});

Related

How do I removeAttribute() hidden from p2? doesn't seem to do anything as is

I'm trying to change the attribute of an object with removeAttribute to take away the hidden status of it but so far nothing seems to work.
My code seems to have no effect. Am I doing something wrong?
function changePage() {
document.getElementById.("p2");
p2.removeAtribute.("hidden") ;
}
I've also tried it all on one line as well like so
function changePage() {
document.getElementById.("p2").p2.removeAtribute.("hidden") ;
}
I've never seen the use of dots before opening parentheses.
E.g.
document.getElementById.("p2").p2.removeAtribute.("hidden") should be document.getElementById("p2").removeAtribute("hidden")
(You are also referencing the element by id after you just retrieved it, which is unnecessary.)
Your first example didn't work because you retrieved the element and did nothing with it, then tried to access a p2 variable that wasn't declared. Again, you also have the . before parentheses.
Here's the js example:
function changeVisibility()
{
var p2 = document.getElementById('p2');
switch (p2.style.visibility)
{
case 'hidden':
document.getElementById('p2').style.visibility = 'visible';
break;
case 'visible':
document.getElementById('p2').style.visibility = 'hidden';
break;
}
}
<div id="p2" style="visibility:hidden">
test
</div>
<br />
<button onclick="changeVisibility()">
change visibility with basic js
</button>
And here's the jQuery example:
function changePage()
{
$('#p2').toggle();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p2" style="display:none">
test
</div>
<br />
<button onclick="changePage()">
change visibility with basic js
</button>
The basic JS version uses the visibility style, and you can see that it doesn't collapse the element, it only makes it invisible.
jQuery has a nice built-in .toggle function that changes the display of the element. If it is hidden, it collapses the element. When the element is displayed, it is re-assigned whatever the display style is for that element. Building that in basic js would take a lot more work, as you are then tracking state (if you want to make the method reusable). You can make jQuery work similarly to the basic js version if you use the css properties, but toggle is quite nice and simple.
Your main issue is that you were mixing the getting of the element with methods that are only available on jQuery objects. I suggest reading the jQuery tutorials for basic accessors, which can get elements by id, class name, etc.

javascript onclick function to enlarge text

I'm not sure why, but I can't seem to get this to work.
Here is my function to enlarge my font.
<script type="text/javascript">
function growText() {
var text = document.getElementById("t_left_text");
text.font-size=22px;
</script>
And here is where I call it
<div id="t_left" onclick="growText()">
<br />
<p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
<br />
</div>
Try:
text.style.fontSize = "22px";
DEMO: http://jsfiddle.net/C2MWN/
When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.
While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class. This is especially useful when setting multiple CSS properties. The class could be defined as:
.enlarged-font {
font-size: 22px;
}
And you would manipulate the text.className property (and/or the classList property).
Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.
Also, don't forget to close your function with a }.
Reference:
style property: https://developer.mozilla.org/en-US/docs/DOM/element.style
classList property: https://developer.mozilla.org/en-US/docs/DOM/element.classList
Use below code
function growText() {
var text = document.getElementById("t_left_text");
text.style.fontSize ="22px";
}
Working example http://jsfiddle.net/D2anZ/
Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)
Fiddle
JavaScript
function growText() {
var text = document.getElementById("t_left_text");
text.className = 'large-font';
}
CSS
.large-font {
font-size: 22px;
}

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

jQuery load issue. Don't know how to approach this AJAX call

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

How to get a DOM Element from a jQuery selector?

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Categories