How to move HTML element - javascript

How to move HTML element to another element. Note that, I don't mean moving element's position. Consider this HTML code:
<div id="target"></div>
<span id="to_be_moved"></span>
I want to move "to_be_moved" to "target" so "target" has child "to_be_moved" now. So the result should be like this:
<div id="target"><span id="to_be_moved"></span></div>
I've searched in google (especially using prototype framework) but all I've got is moving position, not as I want. Thanks before.

document.getElementById('target').appendChild( document.getElementById('to_be_moved') )

Assuming you're working with native DOM elements, the Javascript method .appendChild will suit your needs.
In native Javascript, document.getElementByID is probably your best bet in getting the DOM element, so...
var target = document.getElementById('target')
document.getElementById('to_be_moved').appendChild(target)

Related

Protractor: How to locate a sibling of a given element?

<div>
<a href='...'>LINK</a>
<img class='image' />
</div>
<div>
...
</div>
I want to get a protractor element for the img tag with image class. I already know the link text 'LINK'. In other words, "How do I locate a sibling of a given element?".
The first line of the code could look like this:
browser.findElement(by.linkText('LINK'))
Any ideas?
Thanks & Cheers
Thanks for the inspiration. Here's my solution, not the one I was hoping for, but it works:
element(by.css('???')).element(by.xpath('..')).element(by.css('???')).click();
The chaining and the by.xpath, which allows to get back to the parent are the keys of the solution.
This is what I actually implement on a Page Object:
this.widgets['select-status'] = this.ids['select-status']
.element(by.xpath('following-sibling::div[1]'));
this.widgets['select-status.dropdown'] = element(by.css('.btn-group.bootstrap-select.open'));
The page is based on Bootstrap along with Bootstrap Select. Anyways, we traverse the DOM along the following-sibling axis. Refer to XPATH specification for yourself.
Using Xpath selectors is not a better choice as it slows down the element finding mechanism.
I have designed a plugin to address this specific issues: protractor-css-booster
The plugin provides some handly locators to find out siblings in a better way and most importantly with CSS selector.
using this plugin, you can directly use:
var elem = await element(by.cssContainingText('a','link text')).nextSibling();
elem.click(); //proceed with your work
or, use this as by-locator
var elem = element(by.cssContainingText('a','link text')).element(by.followingSibling('img'));
You can always checkout the other handy methods available here...
Now, you can find web elements such as:
Finding Grand Parent Element
Finding Parent Element
Finding Next Sibling
Finding Previous Sibling
Finding any Following Sibling
Finding First Child Element
Finding Last Child Element
And, guess what, everything you can find using 💥 CSS Selectors 💥
Hope, it will help you...

Cannot remove DOM Element (JavaScript, CreateJS)

I have a problem removing a DOMElement from the stage.
This is how I created my domElement with createjs Framework.
this.domElement = new createjs.DOMElement(document.getElementById('nickname'));
this.domElement.x = 580;
this.domElement.y = 200;
this.stage.addChild(this.domElement);
My HTMl code looks like this:
<form id="myForm" style="visibility: hidden">
<input id="nickname" value="" size="10">
Everything works fine till I want to remove "domElement" from the stage.
Here is how I attempted it:
this.stage.removeChild(this.domElement);
I also tried other solutions like :
this.stage.parentNode.removeChild(this.domElement);
Do you have an ideea why I am not able to remove this DOM Element?
Thank you in advance for your help
Removing the DOMElement from the Stage will not affect the related html element it wraps. DOMElement is useful for controlling position, transformation, and visibility of an HTML element, but if you remove it from the stage, the html element is not affected, since the element is never really on the stage in the first place.
You will have to manually remove the html element from the browser DOM. Note that the stage is not an HTML element, so it does not have a "parentNode". Instead, something like this might work:
domElement.htmlElement.parentNode.removeChild(domElement.htmlElement);
Cheers.
#Lanny's solution to remove the element from the DOM does work. However, if you wish to use this DOM element again, then it will be gone. Therefore, I have found making the element hidden is a better solution, in my case anyway.
domElement.htmlElement.style.visibility = "hidden";
If you no longer have a reference to the createjs DOMElement, then you can access it this way:
document.getElementById("_id_").style.visibility = "hidden";

How to change the background of a specific div when clicked

Note: I don't know jQuery so please don't give me an answer how how to do it using jQuery.
I have multiple divs. I want to know how I could access it and change its specific color when clicked using JavaScript.
I am not looking for a solution like document.getElementsByTagName("div")[0] because it requires inputting a seperate number for each div.
I was hoping there was a simple solution somewhat like this.
<div onClick="change();"><h1>Hi</h1><div>
<div onClick="change();"><h1>Hi</h1><div>
<div onClick="change();"><h1>Hi</h1><div>
<script>
function change(){
this.style.backgroundColor = "red";
}
</script>
Since you don't want to learn jQuery (or presumably, non-inline events), consider:
<div onclick="change(this)"><h1>Hi Dave!</h1></div> <!-- use closing tags -->
<div onclick="change(this)"><h1>Hi Thomas!</h1></div>
function change(elm) {
elm.style.backgroundColor = 'red'
}
Note that the context (this) of the inline event handler code (as specified in the attribute) is the element which was the target of the event - for this case it will be the specific DIV element that was clicked. We then simply pass the element into the callback function so we can use it generically.
Also, in the initial markup, the div elements were not closed and led to nesting. With the corrections, the above approach works to complete the task. (The fiddle code assigns to window.change directly, but it's otherwise the same concept.)
Of course, learning jQuery (or a different) high-level framework will probably pay off quite quickly. Using inline event-handlers is .. very "old school".
This would be more easy.
<div onclick="changeColor(this)">Some text!</div>
<p>A paragraph, that will have no change by click</p>
For JavaScript write this:
function changeColor(div) {
div.style.backgroundColor = #hexvalue
}
This will change the background color of the div and not the <p>. You can set any css value for any element by using this jQuery code.
However, for me the jQuery was pretty easy! :) But as you wish.

What if I don't declare an ID in <div>?

How can I access any <div> if I don't declare the id attribute. Does DOM create ID itself?
e.g.
<div class="common_class" onmouseover="know_your_div(this)">
</div>
<script type="text/script">
function know_your_div(obj){
/*
Here i want to access the div object not by class because of it's common
for all div
*/
}
</script>
Well, the answer to your question is right there in your code.
The obj parameter that your know_your_div function takes is supplied as this in the onmouseover attribute. Thus, that is your div.
There's not an easy way to get to it in all browsers. Your best bet is to just create an ID on it. Is there a reason you can't?
Short of that, you have to navigate to it using DOM traversal methods, which are horribly unstable if your DOM structure changes at all. Code like:
document.body.childNodes[3].childNodes[2].childNodes[4];
or
document.getElementsByTagName('DIV')[22]; // 23rd DIV in the page
etc...
The answer is in your Question, let me try to help you
<div class="common_class" onmouseover="know_your_div(this)"> </div>
var oldObject = "";
function know_your_div(obj) {
// write ur condition if/ese/while/..
obj.parentNode.do_Something(); OR obj.parentNode.ID/Class/value
oldObject = obj;
}
then I guess you need to specify the ID explicitly alongside the class name..DOM won't create the ID itself...
Then it's time to use the DOM. Maybe you could use things like firstChild, lastChild, nextSibling.. http://de.selfhtml.org/javascript/objekte/node.htm
If you're using a JS library, like MooTools or jQuery, which I reccomend, you'll have a lot of powerful selector magic at your hands (example http://mootools.net/demos/?demo=Slick.Finder).
Why not use JQuery and selectors?
http://api.jquery.com/id-selector/
No, the DOM does not create an ID. You need to add an ID. You can use jQuery to access a div by it's class.

Get the HTML that makes up an element in Jquery or Javascript?

How do I get the HTML that makes up an element using Jquery or Javascript?
For example if I have an element that looks like
<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>
I can grab a reference to it using
var x = document.getElementById("theDivIWant")
or $("#theDivIWant")
but how can I actually retrieve the string?
"<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>"
the outerHTML property will give you what you want in IE; in webkit and firefox, you can get the innerHTML of the parent and filter it:
var whatYouWantPlusItsSiblings = $('#target').closest().html();
From there, you can strip the content you don't need. Alternatively, if you have control over the markup, you can surround your target with another well-known element and get that parent's innerHTML.
You could implement outerHTML with jQuery.
if it is the only child of its parent, this should work:
$('#theDivIWant').parent().html();
If it is not the only child, you may be able to combine the above code with some regex to extract only it from the results.

Categories