move node from second to first - javascript

Just want a function that move second node to be a first node.But it not working, any suggestion?
var node = document.getElementById("ir");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.firstChild);
}
fullcode:
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.previousSibling);
}

http://jsfiddle.net/joeframbach/JSZPy/
The issue with the html in that fiddle is the spaces. childNodes[0] matches the first set of spaces, and childNodes[1] matches the first element. Perhaps this is your issue.
<div id="ir">
<p>First</p>
<p>Second</p>
</div>
var node = document.getElementById("ir");
var first = node.childNodes[1];
var second = node.childNodes[3];
node.insertBefore(second,first);

I'm a bit slow today, but I think your use of previousSibling is wrong. I think it should relate to the child node cx not the parent node .. so you should be using cx.previousSibling not node.previousSibling - I've edited mt previous example to remove my original dumb response ... try this ...
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,cx.previousSibling);
}
Two Days Later Edit !!! ....
Of course the example I gave above will not swap the P element and the image because the image's true previousSibling is a newline character between the /P tag closure and the image. More importantly from a coding perspective, it won't work because there isn't an object called 'img' defined anywhere ... so I offer this as a working alternative :
<script>
function swapDivs(obj) {
if(obj.previousSibling){ // if it's null, then it's already the first element //
obj.parentNode.insertBefore(obj, obj.previousSibling);
}
}
</script>
<div id="ir">
<p id="ie">test</p><img src="http://i2.ifrm.com/4639/142/emo/drool.gif" onclick="swapDivs(this);" />
</div>
It doesn't address the newline issue, I just reformatted the HTML.
However, it does resolve the img issue, and provides a generic way of adding the function to any clickable DOM object without having to customise the function.
I'll leave it to you to work out how to get over the problem with the newline/whitespace sibling, but it shouldn't be to difficult. Here's the fiddle to play with if you want to test your attempts ... http://jsfiddle.net/radiotrib/ps9XZ/

You've got an answer but i recommend doing something like:
var node = document.getElementById("ir");
var childs = node.getElementsByTagName("div");
var cx = childs[1];
function der()
{
node.removeChild(cx);
node.insertBefore(cx, childs[0]);
}
der();

I advise you not to put spaces or breaklines when working with childnodes, because they are considering like child of text type. I hope this code will help you:
Javascript code:
function change(){
var parent = document.getElementById("ir");
var img = parent.childNodes[1];
parent.removeChild(img);
parent.insertBefore(img, parent.firstChild);
}
HTML code:
<div id="ir"><p id="ie">test</p><img src="test.gif"></div>
<button onclick="change()">Change</button>

Related

why dont work insertAfter function in javascript

but insertbefore work
var a=document.querySelector("#div");
var y=document.createElement('p');
y.innerText='yazilarucun';
var c=document.querySelector(".p");
a.insertAfter(y,c);
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
Your Problem Can be fixed pretty easily. You can fix this by adding the node before the node that is after the the node
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
//Create Element
var new_para = document.createElement('p');
new_para.innerText = 'yazilarucun';
//Add the element
var old_para = document.querySelector(".p");
insertAfter(new_para, old_para)
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
The node.insertAfter() is not an inbuilt javascript method, instead we created a user-defined function.
<!DOCTYPE html>
<html>
<body>
<p id="point">Start</p>
<script>
var parentNode = document.getElementsByTagName("body")[0];
var refNode = document.getElementById("point");
function insertAfter(newNode, refNode){
refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
}
var newNode = document.createElement("p");
var textnode = document.createTextNode("End");
newNode.appendChild(textnode);
insertAfter(newNode, refNode);
</script>
</body>
</html>
check : https://www.wikimass.com/js/node-insertafter
There is at least 3 ways to do it.
let targetNode = document.querySelector('#wrapper'),
placeNode = document.querySelector('#footer');
targetNode.after(placeNode);
targetNode.insertAdjacentElement('afterend', placeNode);
targetNode.parentNode.insertBefore(placeNode, targetNode.nextSibling);
The first of these 3, is the newest and simplest. Has been supported since Chrome 54+, Firefox 49+, Edge 17+. No IE support...
Last one is best support, oldest and most complicated one...
Middle one is somewhere in the middle... Is still too hard... Not intuitive enough...

Extract innerHTML from a Javascript function

I apologise in advance if this has already been asked, but I couldn't find it. If it has, please direct me to the page and I won't bother you.
I've used a Javascript function to extract inner HTML. I'm able to console.log this, but I'd like to insert it in a new node/part of the HTML.
For example:
<h2>Example text id="article"</h2>
<p>'insert javascript text'</p>
<p>example</p>
<p>example</p>
<p>example id="pToExtract"</p> <--! this is the text i'd like to extract. I would like to feature it higher up in the html page, as well as here. -->
this is the function i've used to extract the text:
function printFirstLine(elem) {
let firstLine = document.getElementById(elem);
console.log(firstLine.innerHTML)
}
printFirstLine ("pToExtract")// this works. i can see the text in the console
the function i've used to place it where i'd like is:
let newText = '';
let menu = document.getElementById ('article');
let li = document.createElement('p');
li.textContent= newText;
menu.insertBefore(li, menu.firstElementChild.nextSibling);
this sort of works if i put text/a string on 'newText', and if I put the function name there it just returns the function, ie function () {} etc.
is there anyway to return the actual value/innerHTML of the function to say a new variable, so i can use it in the place of newtext or another way to accomplish this.
thank you
Not sure if I understand your question correctly but are you looking for this?
function printFirstLine(elem) {
const firstLine = document.getElementById(elem);
return firstLine.innerHTML; // here return the value
}
const newText = printFirstLine( 'pToExtract' );
Also I think you meant to write this:
<p id="pToExtract">example</p>
Instead of this:
<p>example id="pToExtract"</p>

I am trying to trim the output of a jQuery function

I am modifying a third-party script so that I can style the output.
Here is a segment of the original code:
var tip_content = $('<div>').addClass('tip_content').load(url, function() {
Which produces this output:
<div class="tip_content">
I need to add another class to the output to style it differently on each page. Therefore, it seems like a good solution to add the current html page file name as a class.
But I have no experience with JS.
Here is what I've managed to mangle together:
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href')).load(url, function() {
Which produces this:
<div class="tip_content tickets.php?id=185">
This is almost exactly what I need. But I would be very grateful if someone could demonstrate how to trim the output to:
<div class="tip_content tickets">
You have to split the URL with . and takes the first-value from the splited array and add it to the div as second class.
Do it like below:-
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href').split('.')[0]).load(url, function() {
A hard-coded example:-
var hrefs = "tickets.php?id=185";
$('div').addClass('tip_content '+hrefs.split('.')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Inspect and check my class</div>
try below code
s = elem.attr('href');
s = s.substring(0, s.indexOf('.'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {
I would like to add a modification to be safe. suppose your url is: tickets.sold.php and you want tickets.sold. In this case you should try this:
s = elem.attr('href');
s = s.substring(0, s.indexOf('.php'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {

Getting the width of child element pure javascript

Html:
<div class="project-box">
<img src="img/ifix.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of title</p>
</div>
</div>
javascipt:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.clientWidth);
};
I'm trying to get the img width and eventually the img height using pure JavaScript I know this is a lot easier with jQuery but I want to do it using only JavaScript.
EDIT:
I realized I was not specifying the array for the img and project
working js:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
alert(img[0].offsetWidth);
};
Both getElementsByClassName and getElementsByTagName returns an array of objects, so you need to access the actual element by its index then call its methods/properties
window.onload = function () {
var project = document.getElementsByClassName('project-box')[0];
var img = project.getElementsByTagName('img')[0];
alert(img.clientWidth);
};
Demo: Fiddle
I believe project.getElementsByTagName('img'); is returning an array, even if it only has one object.
Try something like
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.pop().width); //This should remove the element from the array and then call width
};
Try this one:
alert(img.clientWidth);
The reason this is not working is because .getElementsByClassName() and .getElementsByTagName() both wrap elements inside an [object HTMLContainer], you need to select the first element from each of these objects.
This code should work:
window.onload = function()
{
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
console.log(img[0].clientWidth);
};

javascript document.getElementById not working

Following is my javascript program. I am trying to get all child tags of parent div tag but when I am running the program document.getElementById('abc') returning null.
function init(){
// currentDiv = document.getElementById("intro");
alert("working");
count = 0;
divs = document.getElementById('abc').getElementsByTagName("div");
alert("HI " + divs)
currentDiv = divs[count];
nextDiv = divs[count + 1]
count = count + 1;
}
window.onload = init();
Following is my div tag definitions:
<div id='abc'>
<div></div>
</div>
thanks.
The problem is in this line:
window.onload = init();
You are running init and setting the return value as the value of window.onload. My guess is that the code is being executed before the DOM is ready, i.e. before the divs exist.
Try this instead:
window.onload = init;
I suggest you start using jQuery instead, then you have much more powerful tools for this kind of DOM search/traversing
<body onload="init()">
<div id='abc'>
<div></div>
</div>
</body>
this probably solves your problem

Categories

Resources