how to get element id of div and appendChild html to it - javascript

I want to get the ID of a div using JavaScript that runs inside that div. I want to appendChild() html to that div.
eg:
<div id="randomnumber">
<script type="text/javascript">
var htmlcontent = "abcdf";
//need the id of div holder
var thisDIVid= ?????;
// appendChild to this div
?????.appendChild(htmlcontent);
</script>
</div>

If you know where in the structure your div is placed you can access it like this:
var mainDiv = document.getElementById('mainDiv');
yourDiv = mainDiv.getElementsByTagName('div')[number];
number is the place in the structure

document.getElementyById("yourDivId"); will find any div with an unique ID.
var div = document.getElementyById("yourDivId");
div.appendChild("yourContent");

Related

How to modify HTML attributes inside a variable that contains HTML?

I have a variable that contains some HTML elements & content:
var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';
What I'd like to do is modify the data-id within the #div-element.
What I've tried so far:
console.log($(data).find('#div-element').attr('data-id'));
This returns undefinied.
data = $.parseHTML(data);
console.log($(data).find('#div-element').attr('data-id'));
Tried to parse the HTML also, but it returns undefinied as well.
What am I missing here?
I'm using jQuery but a Javascript solution is just as good.
The issue is because you're using find() yet there is no root element in the HTML string you're specifying; all the elements are siblings. In this case you can use filter():
var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';
var id = $(data).filter('#div-element').data('id');
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Also note the use of data('id') over attr('data-id').
Create a dummy element div and set data as its innerHTML
var html = `<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>`;
var div = document.createElement( "div" );
div.innerHTML = html; //set the html string
//change the attribute of the id-Element
div.querySelector( "[id='div-element']" ).setAttribute( "data-id", "2" );
console.log( div.innerHTML );
In this case following will work.
$("<div>" + data + "</div>").find('#div-element').attr('data-id')

How to wrap the content of DOM Element into another Element with minimal performance overhead?

I would like to wrap the live content of a DOM element into another, keeping all the structure and all attached event listeners unchanged.
For example, I want this
<div id="original">
Some text <i class="icon></i>
</div>
to become
<div id="original">
<div id="wrapper">
Some text <i class="icon></i>
</div>
</div>
Preferably without jQuery.
If there is nothing else other than ID to distinguish your nodes, and given that #original has multiple child nodes, it would probably be simpler to create a new parent node and insert that:
var original = document.getElementById('original');
var parent = original.parentNode;
var wrapper = document.createElement('DIV');
parent.replaceChild(wrapper, original);
wrapper.appendChild(original);
and then move the IDs to the right place:
wrapper.id = original.id;
original.id = 'wrapper';
noting of course, that the variables original and wrapper now point at the 'wrong' elements.
EDIT oh, you wanted to leave the listeners attached... Technically, they still are, but they're now attached to the inner element, not the outer one.
EDIT 2 revised answer, leaving the event listeners attached to the original element (that's now the outer div):
var original = document.getElementById('original');
var wrapper = document.createElement('DIV');
wrapper.id = 'wrapper';
while (original.firstChild) {
wrapper.appendChild(original.firstChild);
}
original.appendChild(wrapper);
This works simply by successively moving each child node out of the original div into the new parent, and then moving that new parent back where the children were originally.
The disadvantage over the previous version of this answer is that you have to iterate over all of the children individually.
See https://jsfiddle.net/alnitak/d0jss2yu/ for demo
Alternatively, do it this way. It also displays result in the adjacent result div.
<div id="original">
Some text <i class="icon"></i>
</div>
<button onclick="myFunction()">do it</button>
<p type="text" id="result"></p>
<script>
function myFunction() {
var org = document.getElementById("original");
var i = org.innerHTML; //get i tag content
var wrap = document.createElement("div"); //create div
wrap.id="wrapper"; //set wrapper's id
wrap.innerHTML= i //set it to i tag's content
org.innerHTML=""; // clear #orignal first
org.appendChild(wrap); //append #wrapper and it's content
var result = org.outerHTML;
document.getElementById("result").innerText = result;
}
</script>
Updated answer:
This should work better and with less code than my previous answer.
var content = document.getElementById("myList").innerHTML;
document.getElementById("myList").innerHTML = "<div id='wrapper'></div>"
document.getElementById("wrapper").innerHTML = content;
EDIT: This will destroy any event listener attached to the child nodes.
Previous answer:
I don't tried it, but something like this should work:
var wrapper = document.createElement("DIV");
wrapper.id = "wrapper";
var content = document.getElementById("myList").childNodes;
document.getElementById("myList").appendChild(wrapper);
document.getElementById("wrapper").appendChild(content);
Create the wrapper element.
Get myList contents.
Add the wrapper element to myList.
Add myList contents to be child of the wrapper element.

Add new parent div and next a div inside this parent div

I want to do a simple manipulation but i don't understand why it's don't work i have a div :
<input type='button' value='validate' class='popupjq'>
And i want to add a parent div to this input and also a 'brother' div for have this result :
<div id = 'id_parent'>
<input type='button' value='validate' class='popupjq'>
<div id = 'id_brother'></div>
</div>
So i use this javascript :
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'>");
var divCache = $("<div id='toto'>");
$(this).wrap(divParent);
$(divParent).append(divCache);
});//bracket missing
My problem is that the parent div is create but not the brother div.
You can use insertAfter() to put the second element where you require:
$(".popupjq").each(function() {
$(this).wrap('<div id="id_parent" style="display: inline-block; position: relative;"></div>');
$('<div id="toto"></div>').insertAfter(this);
});
Example fiddle
You haven't closed your each-loop properly (check brackets).
You should specify the DIVs' HTML as strings.
Using "each" implies you're
planning to apply this method on several elements. In this case you
should work with classes instead of IDs in your DIVs' HTML, since IDs
are meant to exist exactly one time in the DOM.
You haven't addressed your parent DIV properly (see my approach).
http://jsfiddle.net/1yn8qgg3 (CSS with background colors to visually mark the DIVs)
$(".popupjq").each(function() {
var divParent = "<div class='class_parent'></div>";
var divCache = "<div class='class_toto'></div>";
$(this).wrap(divParent);
$(this).parent().append(divCache);
});
Hope this helps.
Do the following, to get the result
$(function(){
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'> </div>");
var divCache = $("<div id='toto'> </div>");
$(this).wrap(divParent);
$(this).append(divCache);
});
});
Fiddle

How to get id's of multiple divs on clicking one div

I have following code
<div id = "fa10_holder">
<div id = "b-1"></div>
</div>
I am adding this dynamically in a div that holds all of these type of divs ..
lets say if I add another div it would be like this
<div id = "fa11_holder">
<div id = "b-2"></div>
</div>
Now the problem is when I click the div with id of b-1 or b-2 and so on I want the id of its parent like fa10_holder and the id of the clicked div aswell... can any one help me ??
Like this working demo another way.
APIs:
parents - http://api.jquery.com/parents/
attr or prop - http://api.jquery.com/attr/ or http://api.jquery.com/prop/
I have added extra class, in case you have many div you can have a blanket click via class. :)
Extra: When to access the attribute (vs the property)?
code
$(document).ready(function () {
$(".hulk").click(function () {
alert($(this).parents('div').attr('id'));
alert($(this).attr('id'));
});
});
html
<div id = "fa11_holder"> parent
<div id = "b-2" class="hulk">hulk</div>
</div>
var thisid = this.id;
var parrentid = $(this).parent().attr('id');

Why won't this script append a child div element?

When I click on the p element with an onclick attribute calling the make_child function I would expect it to append a div element when ever it is clicked but it seams to be only appending a text node to the paragraph element what is the cause of this?
<script type="text/javascript">
function make_child(text, id, type) {
var text = document.createTextNode(text);
var target = document.getElementById(id);
var add = document.createElement(type);
var addtext = add.appendChild(text);
target.appendChild(addtext);
}
</script>
<p id="changeme" onclick="make_child('I have changed', 'changeme', 'div')">Click me to change</p>
change the last line to this
target.appendChild(add);
now you are appending to the correct element
Try doing target.appendChild(add) instead of target.appendChild(addtext)
Edit (more detail):
The syntax for appendChild (from MDN) is:
var child = element.appendChild(child);
Where child is the element being appended. In this case, addtext = add.appendChild(text) is set to text rather than add. Just doing target.appendChild(add) should solve this problem.
This also means the variable addtext is useless; you can remove it leaving only
add.appendChild(text)
for that line.

Categories