I have this code below..
<script> document.getElementById('example').style.background-color =
'#FFCC00';
</script>
<div id="example">This is an example.</div>
why does not it work?
The script runs before the element with the given id exists, and you have a DOM property name with a hyphen in it (which gets treated as the minus operator).
<!-- Put the element first -->
<div id="example">This is an example.</div>
<script>
// camelCase CSS property names when converting to DOM property names
document.getElementById('example').style.backgroundColor = '#FFCC00';
</script>
See a live example of the above snippit.
Instead of putting the element first, you can wrap your JS statement in a function and then call it after the element exists. You can have this happen automatically by binding it as an event handler to something suitable (such as the document load event).
You should write backgroundColor
2 things that need to change in your code.
As is, your code is in the wrong order. You need to have the HTML first and then the JS. The element doesn't yet exist in this order, the JS is being executed first and the DOM object is not yet there.
There is no "background-color" property. Instead use ".backgroundColor". The dashes are usually replaced with camel casing.
Here is a working example:
<div id="example">This is an example.</div>
<script>
document.getElementById('example').style.backgroundColor = '#FFCC00';
</script>
Another tip:
If you want to remove the order as a dependency, you can wrap the JavaScript in a "onload" event handler.
Change the <script> to be below your element and use backgroundColor
<div id="example">This is an example.</div>
<script>
document.getElementById('example').style.backgroundColor ='#FFCC00';
</script>
Update:
<div id="example">This is an example.</div>
<script>document.getElementById('example').style.setProperty('background-color','#fco','important');</script>
,'important' is not required
Related
<div id="TheDivIWantTheBelowScriptToAddress"></div>
<script>
document.getPreviousDiv().innerHTML = "YADDA"
</script>
Now I know that in JS I can easily reference an element by its ID like document.getElementById("blah").
However, when the page is being generated from templates, it sometimes might get tricky to ensure that the ids won't repeat. It would be more convenient if I could just reference the first element of a given type (like div or canvas) that lies before the script tag in which this script is included.
Can this be somehow done or do I have to write extra logic to ensure the uniqueness of divs?
I should use this:
<div></div>
<script>
document.currentScript.previousElementSibling.innerHTML = "blah";
</script>
The currentScript gets the current script element.
The previousElementSibling gets the previous element.
This looks like a job for .prev
$('selector').prev()
EDIT: and again without jquery:
var x = document.getElementById("item2").previousSibling.innerHTML;
Is it possible to trigger a Javascript script, when an input element or any other html element is rendered. This script should be triggered from within the html tag, so that we should be able to pass 'this' to the js function.
No, there is no such event.
However, a <script> tag placed directly after the HTML element would have a similar effect: It would be executed directly after the element has been rendered:
<input type="text" id="input123" value="Hello World!">
<script>
alert("Input123 is now ready:"+document.getElementById("input123").value);
</script>
In most cases, however, it is best to use the document-wide load (or DOMReady, or jQuery's .ready()) to start any script operations. The DOM will be fully ready then.
A way to simulate such an event is to create a custom data-* atttribute (HTML-5 valid) and use that as a selector. Then in the main javascript code, you can add a selector for anything which has this specific data-XXX attribute and evaluate the javascript code inside.
Example HTML code:
<div data-onload="sampleFunction('param1', 2)"></div>
Example Javascript code (using jQuery). It is also possible to use normal DOM to find elements with this attribute.
/* Find any element which has a 'data-onload' function and load that to simulate an onload. */
$('[data-onload]').each(function(){
eval($(this).data('onload'));
});
This works well. I actually use it in production.
No. However, any script placed after the markup of the input element, will be run with the input element available because it is parsed before the script. So, if this was all in the body:
<input id="a">
<script>document.getElementById('a');</script>
That would all work anyway.
I have an input element that gets dynamically added to the document and needs to get initialized.
It's not perfect, but here's a way to initialize the widget the first time the input is used:
<input onfocus="initwidget(this)">
There is a trick. There are onload and onerror events for inputs have type="image" src="..." attributes. You can use onerror by passing empty or always wrong to src and change the type to proper one when onerror event triggred:
function func(input) {
console.log("Input loaded");
input.type = "text";
input.value = "Worked!";
input.removeAttribute("src");
// ...
}
<input type="image" value="" onerror="func(this)" src=""/>
No this is not possible. You could however use jQuery + $(document).ready(function) to modify any input field you want right after the page has finished loading.
No, there is not. Just run your code from the document "ready" handler, or use something like jQuery to give you a way to run code at "ready" (which is when the DOM is complete but images may not have loaded).
I never really understood what's happening behind the behavior of dynamically created elements. Here's an example:
$('.some-list').append('<div class="node"></div>');
Where is that stored now? How can I access the div element $('.node')?
I know jQuerys 'on' method for events, but how do I simply access and manipulate that element? Thanks.
Whether $('.some-list') is itself present in the document, or not, you could simply use:
$('.some-list')
// append returns the original collection ("$('.some-ist')"),
// not the newly-added element(s)
.append('<div class="node"></div>')
// so here we can use "find('.node')" to find the newly added
// element(s):
.find('.node')
In the event of the $('.some-list') being present in the document already:
$('.some-list').append('<div class="node">The newly-added Element</div>').find('.node').css('color', '#f90');
.some-list div {
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-list">
<div>Existing node</div>
</div>
In the event of the $('.node') element not being present in the document:
var someList = $('<div />', {
'class': 'some-list',
'html': '<div>Existing element</div>'
}),
newNode = someList.append('<div class="node">The newly-added Element</div>').find('.node');
console.log(newNode);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
References:
append().
css().
find().
So lets analyse what would happen behind the scenes here.
First we need to understand the HTML that'd look something like below.
<html>
<head>
<!-- Some code here -->
</head>
<body>
<!-- Some Code here -->
<div class="some-list"></div> <!-- Assuming it to be div as that's the most generic way I'd explain, but it could be any element for that matter -->
<!-- Some Code here -->
</body>
</html>
Notice that when you write the $('.some-list'), JQuery will select the div with class=some-list and then you append a random string inside that by .append('<div class="node"></div>'); now when you use JQuery's append, it'll try to see if the passed data (in this case a string) is an object or not. if object it internally does element.appendChild else it internally does element.innerHTML=string.
Now to access the element you write $('.node') as it means you are trying to get the elements from the dom with class names as node. Since you do this after .append it becomes available in the DOM and you can now access it as any other element that was already present in the DOM.
Note: The Confusion is caused as most of the times the event attachment happens at document ready and these dynamically created elements are added later and do not trigger these events. In order to avoid these scenarios Use delegations. Look for JQuery's .on method in detail.
You simply just use $('.node')....
But i think you understand that you can't manipulate a element that doesn't exist yet (you cant access .node before it's appended)
How do you insert an HTML element dynamically (using prototype) at the current position if you don't know the id of the parent element? All examples I've seen assumes the element has some kind of id.
I.e.
<script>
function addSomeHtmlAtCurrentPosition()
{
current_element = ...; // Magic?
current_element.insert(...);
}
</script>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- should insert something here... -->
</div>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- ... and then here -->
</div>
I've tried using prototype with $$('div').last(), but that doesn't seem to work (last() sometimes reports back another div if I use libraries such as livepipe).
What I really want is something similar to document.write, but using prototype instead of raw html.
The only way I can think of is finding the <script> element and insert the element before/after the script. The thing is, all DOM methods need a DOM node to operate on. Executing scripts that modify the DOM before the document has loaded isn't a good and safe idea.
Similar questions linked below.
JavaScript: get the current executing <script> node?
How may I reference the script tag that loaded the currently-executing script?
Is it possible to trigger a Javascript script, when an input element or any other html element is rendered. This script should be triggered from within the html tag, so that we should be able to pass 'this' to the js function.
No, there is no such event.
However, a <script> tag placed directly after the HTML element would have a similar effect: It would be executed directly after the element has been rendered:
<input type="text" id="input123" value="Hello World!">
<script>
alert("Input123 is now ready:"+document.getElementById("input123").value);
</script>
In most cases, however, it is best to use the document-wide load (or DOMReady, or jQuery's .ready()) to start any script operations. The DOM will be fully ready then.
A way to simulate such an event is to create a custom data-* atttribute (HTML-5 valid) and use that as a selector. Then in the main javascript code, you can add a selector for anything which has this specific data-XXX attribute and evaluate the javascript code inside.
Example HTML code:
<div data-onload="sampleFunction('param1', 2)"></div>
Example Javascript code (using jQuery). It is also possible to use normal DOM to find elements with this attribute.
/* Find any element which has a 'data-onload' function and load that to simulate an onload. */
$('[data-onload]').each(function(){
eval($(this).data('onload'));
});
This works well. I actually use it in production.
No. However, any script placed after the markup of the input element, will be run with the input element available because it is parsed before the script. So, if this was all in the body:
<input id="a">
<script>document.getElementById('a');</script>
That would all work anyway.
I have an input element that gets dynamically added to the document and needs to get initialized.
It's not perfect, but here's a way to initialize the widget the first time the input is used:
<input onfocus="initwidget(this)">
There is a trick. There are onload and onerror events for inputs have type="image" src="..." attributes. You can use onerror by passing empty or always wrong to src and change the type to proper one when onerror event triggred:
function func(input) {
console.log("Input loaded");
input.type = "text";
input.value = "Worked!";
input.removeAttribute("src");
// ...
}
<input type="image" value="" onerror="func(this)" src=""/>
No this is not possible. You could however use jQuery + $(document).ready(function) to modify any input field you want right after the page has finished loading.
No, there is not. Just run your code from the document "ready" handler, or use something like jQuery to give you a way to run code at "ready" (which is when the DOM is complete but images may not have loaded).