Any way to take the preceding element? - javascript

<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;

Related

Append dynamic javascript variable to HTML tag. InnerHTML & insertAdjacentHTML both incorrect

I have a couple of javascript variables that are being updated as an animation plays out.
What I'd like to do is append these to HTML elements but I'm having a few problems. I can make it work by introducing a span tag into the HTML and targeting that instead but I'd like to know how I can do it without.
The code that currently works:
<p id="infoCurrentDepth">Current Depth:<span id="bla"></span></p>
var bla = $('bla');
function updateInfoPanel(){
bla.innerHTML = scaleControl.value;
}
I've removed code that isn't required.
What I'd like to do is just append the variable to to the p tag instead. When I try this is repeats the value several times instead of replacing it.
Thanks for any help
Since you are using jQuery there is no need to overwrite $ to create a element selector. Use jQuery id selector along with manipulation methods like .html()/.append() like
So try the below after removing the var $ = function(){...}
$('#infoCurrentScale').append('sdfsdf');

How to find out an element with id partially matched, and change its css style?

I have a website which execute some javascript while loading, which eventually created a div with id "image_XXXXXXXXX", where the XXXXXXXXX are random numbers.
The question is, how can I grab this div, and change its css style after page loaded? For known id, I can use
<script type="text/javascript">
window.onload=function(){
document.getElementById("image").style.zIndex = '9999999999';
};
</script>
However, since the id contains random numbers, I can't use getElementById() anymore. Any suggestions?
Thank you very much.
It's unusual to have an ID that you can't identify, since that sort of defeats the point, but you can use querySelector like so:
document.querySelector("[id^='image_']").style.zIndex = 9999999999;
Another option from querySelector is using match() based on a regex of part of your id.
You need to loop through all the matches and set their zIndex.

what's wrong with this javascript code getElementById?

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

Moving a div from inside one div to another div using Prototype?

In prototype or normal-but-cross-browser-compatible Javascript, how do I move the contents of a div to the contents of another div?
Inside the div is a form with ids and dependent Javascript code with event observers. I don't want this to break just because I have moved a block in the DOM. A 'this innerHTML = that innerHTML' solution is not what I am looking for. I will also be needing to do this when the DOM is loaded.
I want to go from this:
<div id='here'>
<div id='MacGuffin'>
<p>Hello Worlds!</p>
</div>
</div>
<div id='there'>
</div>
to this:
<div id='here'>
</div>
<div id='there'>
<div id='MacGuffin'>
<p>Hello Worlds!</p>
</div>
</div>
...when the document loads with nothing jumping about.
You can add this at the very end of the BODY tag:
<script>
document.getElementById('there').appendChild(
document.getElementById('MacGuffin')
);
</script>
MacGuffin will be moved automatically from one to the other.
And there won't be any flickering.
Perhaps not a major point, but there is no Node.migrateChild() built-in Javascript interface method. If a fragment already has a parent elsewhere in the DOM (as div id='MacGuffin' does in example markup above), appendChild() quietly detaches the argument fragment from any current parent before reattaching under the new parent. In my mind migrateChild() would be a more semantically meaningful method name than appendChild(), less need for StackOverflow developer searches to allude to its more powerful abilities.
To move the contents of here into there, this works, as long as here encloses everything you want to move, like a <div>:
$('there').insert($('here').descendants()[0]);
descendants() returns an array, and insert takes content, so use the first element.
To move the contents of here into there, you're basically after:
$('there').insert($('here').childNodes);
Sadly, that doesn't work.
As with the other two answers, it looks like you have to resort to plain JavaScript with prototype only providing a shorthand for document.getElementById.
var frag = document.createDocumentFragment();
for (var c = $('nav').firstChild, n; c; c = n) {
n = c.nextSibling;
frag.appendChild(c);
}
$('header').appendChild(frag);
(See John Resign's blog for performance stats on DocumentFragments:
http://ejohn.org/blog/dom-documentfragments/)

How to insert an element at the current position in HTML using prototype

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?

Categories

Resources