How to remove a child node keeping his child in javascript? - javascript

I'm not so good in javascript.
I have a DOM structure like this:
<div data-embed-url="https://www.youtube.com/watch?v=5DkrwfY2jw4">
<div class="black">
<div>
<div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 56.2493%;">
<iframe allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/5DkrwfY2jw4"></iframe>
</div>
</div>
</div>
How can I remove the node with the class "black" and the div without style and class keeping the others?

Assuming you are using ES5:
// Find the `.black`
var black = document.querySelector('.black');
// Replace `.black` with its first child
black.parentNode.replaceChild(black.firstChild, black);

You should use ID's on your div's to manipulate the DOM. ID's are meant to be unique. Using classes is discouraged as you can use class on mulitiple DOM nodes.
// Removing a specified element when knowing its parent node
var d = document.getElementById("top");
var d_nested = document.getElementById("nested");
var throwawayNode = d.removeChild(d_nested);
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
An example using your code with div ID:
// Removing a specified element when knowing its parent node
var d = document.getElementById("blackId");
var d_nested = document.getElementById("blackChildId");
var div_i_want = d_nested.innerHTML;
alert('BEFORE: ' + d.innerHTML);
var throwawayNode = d.removeChild(d_nested);
d.innerHTML = div_i_want;
alert('AFTER: ' + d.innerHTML);
<div data-embed-url="https://www.youtube.com/watch?v=5DkrwfY2jw4">
<div class="black" id="blackId">
<div id="blackChildId">
<div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 56.2493%;">
<iframe allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/5DkrwfY2jw4"></iframe>
</div>
</div>
</div>

If your intention is to remove the two div elements, while keeping the nested content (in order to simplify the nesting), then you could use .replaceChild() like this:
var black = document.querySelector('div.black');
var divToKeep = black.children[0].children[0];
black.parentNode.replaceChild(divToKeep, black);

Related

Create a new element div and wrap it around an existing one with JavaScript

I am aware how to create a new div or any other HTML element and add it as a child using pure JavaScript.
Am I able to create a new element and add my existing one into it?
For example:
I would like to take the current code below and put it within a brand new div.
// Current elements on page
<div>
<img />
<img />
</div>
<div>
<p>Hello world</p>
</div>
What I want:
// What I want
<div class="my-new-div">
<div>
<img />
<img />
</div>
<div>
<p>Hello world</p>
</div>
</div>
I understand this is easy to do in HTML however. I have to use JavaScript in this scenario to alter a webpage. In this scenario I must add a parent div to avoid changing styles.
You can simply fetch the existing node, create a new one, insert it before the existing node, and finally append the existing node to the new node as child. The browser moves the node when performing the "append" operation, if it is already contained somewhere in the document.
const myDiv = document.getElementById("myDiv");
const myNewDiv = document.createElement("div");
myNewDiv.style.border = "solid 1px";
document.body.insertBefore(myNewDiv, myDiv);
myNewDiv.appendChild(myDiv);
<div id="myDiv">
<p>Hello</p>
<p>Paragraph</p>
</div>
To move one element from one part of the document to another part, you need to associate the element to a new parent. this automatically disassociates the moving element from its old parent.
function newAndMove() {
//Create a new element
let blue = document.createElement('DIV');
blue.classList.add('blue-div');
document.body.appendChild(blue);
//Move existing element inside it
let red = document.getElementById('old-div');
blue.appendChild(red);
}
.red-div {
width: 200px;
height: 200px;
background-color: red;
}
.blue-div {
width: 400px;
height: 400px;
background-color: blue;
position: absolute;
top: 100px;
left: 100pxl
}
<input type="button" value="Get red inside new blue" onClick="newAndMove()">
<div class="red-div" id="old-div"></div>
you can move DOM elements by appending them as a child to the preferred container.

How to get id of a javascript variable which is html form

I have a javascript variable which is returning as below;
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
I want to get the id(GRID_7_2_1_1_e_4) of this html.
Could you help me?
Assuming you don't have jQuery, you can try this approach:
Idea:
Create an in-memory element and set your HTML string as its innerHTML.
Then navigate to necessary child in this element and fetch required attribute.
Note: This approach will only work if the supplied HTML string is valid. Also note that id should be unique. So if there are multiple elements with same id, first element will be fetched.
Sample
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var div = document.createElement('div');
div.innerHTML = html;
var id = div.firstChild.id;
// or
// var id = div.firstChild.getAttribute('id')
console.log(id);
// This should return `null` as `div` is an in-memory element and will not be a part of DOM tree
console.log(document.getElementById('GRID_7_2_1_1_e_4'))
It can be done with javascript regexp:
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">';
var regex = /id="([^"]*)"/g;
var matches = regex.exec(html);
console.log(matches);
Do you have jQuery running in your app?
If so, than you can use:
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var id = $(html).attr('id');
Check this, this is exact answer to your question using only html and javascript
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var test = html.match(/id="(.*)" /);
alert (test[1]);
}
</script>
</body>
</html>
I Assume that you are not using the jQuery then in this case you can use DOM Praser.
In this case I am using the Object of DOM Parser and then i am using it to convert the string into HTML element. and after converting it. I am finding the id of the element by firstchilid.id assuming that span is your first element
var htmlString = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
parser = new DOMParser();
doc = parser.parseFromString(htmlString, "text/xml");
console.log(doc.firstChild.id);

Can I use JavaScript to set inline style for an element as I am rendering it in the HTML? I would like to define positioning based on a previous div

I have HTML as follows:
<html>
<body>
<div>
things
</div>
<div style='top: [same top as last div - could be anywhere]px; position: absolute;'>
</div>
</body>
</html>
I would like to do something like:
<div style='top: <script>get last div position</script>px'>
</div>
NOTE: I know how to re-position an element after it has already been defined. What I want to do is position the element dynamically as it is being defined. In other words, I don't want to "re-position" the element at all -- I want it to be initially positioned based on the location of a different element.
JQuery's .prev() method will work:
$(element).prev().offset().top
Here is a solution without jquery and without the need for elements to be sequential:
http://jsfiddle.net/johnrbpalmer/w5sck7k3/4/
html:
<body>
<div id="div1">
things
</div>
<div id="div2">
more things
</div>
</body>
JS:
var div1_top = document.getElementById("div1").getAttribute("top");
document.getElementById("div2").setAttribute("top", div1_top);
CSS:
#div1{
top:10px;
left: 10px;
position: absolute;
}
#div2{
right:10px;
position:absolute;
}
UPDATE (based on comment):
I may be misunderstanding what you want, but how about the following:
HTML:
<body>
<div id="div1">
things
</div>
<button id="make_div2_button">
make more things </button>
</div>
</body>
JS:
document.getElementById("make_div2_button").addEventListener("click", function(){
var div1 = document.getElementById("div1");
var top = div1.offsetTop;
var div2 = document.createElement('div');
div2.style.cssText = 'position:absolute; right: 10px; top: ' + top.toString() + 'px;';
var message = document.createTextNode("More things");
div2.appendChild(message);
document.body.appendChild(div2);
})
CSS:
#div1{
top:30px;
left: 10px;
position: absolute;
}
#make_div2_button{
left:10px;
top: 100px;
position:absolute;
}

How to pass a <div> in innerHTML in Javascript

I have following code:
widgetEl.innerHTML = "<h2>" + name + "</h2><h3>Time Series</h3>" ;
It is working fine. I need to pass a div instead of <h3>Time Series</h3>. How can I pass the follwing div instead of <h3>Time Series</h3>.
<div id="test" class="hide" style="min-width: 700px; height: 200px; margin: 0 auto"></div>
Any help please....
I guess you've a quoting problem. Use single quotes around the JS:
widgetEl.innerHTML = '<h2>' + name + '</h2><div id="test" class="hide" style="min-width: 700px; height: 200px; margin: 0 auto"></div>';
Or if the div is a real HTML element:
widgetEl.innerHTML = '<h2>' + name + '</h2>' + document.getElementById('test').outerHTML.replace(/id\="test"/, 'id="test2"');
Notice, that in the latter case you have to change the id of the div to avoid double ids.
Because it is unclear of what you are wanting to do, here are several attempts at what you are doing using different techniques for different situations
To concatenate the dom string, use single quotes when needing to use double in the string
widgetEl.innerHTML = "<h2>" + name + "</h2>"+'<div id="test" class="hide" style="min-width: 700px; height: 200px; margin: 0 auto"></div>';
To replace the h3 with a existing div element, using replaceChild
var test = document.getElementById("test");
var h3 = widgetEl.getElementsByTagName("h3")[0];
widgetEl.replaceChild(test,h3);
Another way, use remove() to remove old element, and then appendChild to append the div
Of course using this way may not lead to what you want as there could be other stuff around the h3, just assuming the string in your example is what is currently in the div.
var test = document.getElementById("test");
widgetEl.getElementsByTagName("h3")[0].remove();
widgetEl.appendChild(test);
If needing to clone
var test = document.getElementById("test");
widgetEl.getElementsByTagName("h3")[0].remove();
widgetEl.appendChild(test.cloneNode());
Also remember to change the ID as all id's need to be unique
var clone = document.getElementById("test").cloneNode();
clone.id = "someOtherUniqueID";
var h3 = widgetEl.getElementsByTagName("h3")[0];
widgetEl.replaceChild(clone,h3);
Also note the use of getElementsByTagName will try to get any element with tag name h3, I am assuming here that it is the only one in that element, you will have to add other measures to make sure you are getting the right one if there are other h3 elements.
document.getElementById("content-11").innerHTML = '<div v-bind:style="stylesFontSize">'
+ '<p v-bind:style="stylesMessage" class="c-ecard__message" style="overflow: hidden; position: absolute; width: 69.7%; max-width: 57.7%; height: 68.3%; left: 42.1%; top: 0.8%; line-height: 1;" v-html="this.$options.filters.newline(preparedMessage)"></p></div>';

catching DOm elements

hi Guys I need help with catching a img tab in side of the p tag
this is my html
<p>
<img style="max-width: 100%; margin-left: auto; margin-right:
auto; display: block;"
src="../content_platform_node/content_primitive/51e4c3e29306e2581000000a/blob"
alt="" data-lscp-resource-mimetype="image/jpeg"
data-lscp-resource-id="51e4c3e29306e2581000000a" />
</p>
what I need is to wrap the img tab with a tag instead of p tag , note this is not pre-generated its user input content therefore I need to do this with jquery or javascript
help needed
You can try something like
var parent = $('img').parent();
parent.wrap('<div />').contents().unwrap()
and the div can be any other tag
var image = $('img[data-lscp-resource-id="51e4c3e29306e2581000000a"]');
image.parent('p').replaceWith($('<a></a>').html(image));
Fiddle
EDIT: raw js:
var image = document.getElementsByTagName('img')[0];
var oldParent = image.parentNode;
var newParent = document.createElement('a');
newParent.appendChild(image);
oldParent.parentNode.appendChild(newParent);
oldParent.parentNode.removeChild(oldParent);
Fiddle

Categories

Resources