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

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

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.

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

How can I add my own <divs> to a container dynamically?

I found a lot of info about this, but I haven't foundanything that could help me yet.
My problem is that I have got a div with its id and it supposes to be a container (#cont_seguim).
I have a menu on the right side which contains circles (made by css and filled with text), like following:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
where b and n are the format for background and text.
When I click a circle, this one must be added to the container (notice that each circle has got its own text), but I can't get that.
I made and array and used alert() to test that click works, and it does, but append() doesn't even work to print text, and I don't know why.
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
Thank you for your responses!
Your code seems to work fine (if you fix the different class name used in html vs script circulo_menu vs circle_menu)
Demo at http://jsfiddle.net/7jbUj/
To add the whole circle append the whole element and not its text by using .append(this)
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
Demo at http://jsfiddle.net/7jbUj/1/
To add a copy of the circle, so you can add multiple of them use the .clone() first..
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
Demo at http://jsfiddle.net/7jbUj/3/
Inside the click handler, this refers to the clicked element. And since you bind the click handler on the circle_menu element, this refers to that. You can use it directly for the appending or clone it to make a copy first..
unable to understand properly, hope below one can help you.
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
make sure classname and id name will remain same as html
Try using html() instead of text().
Try this: Demo
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
Try this:
$( ".container" ).append( $( "<div>" ) );
source
use
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
You could try
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
By this way the clicked circle element get added to div

How to check if an element with id exists or not in jQuery?

I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?
If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div> into the document.
One options is to use a custom event as a pub/sub.
$(document).on('document_change', function () {
if (document.getElementById('liveGraph_id')) {
// do what you need here
}
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
$(this).trigger('document_change');
});
If it is added dinamically, you have to test again. Let's say, a click event
$("#element").click(function()
{
if($("#liveGraph_id").length)
alert("HHH");
});
How you inserting your dynamic generated div?
It works if you do it in following way:
var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
alert('exists'); //wont give alert because it doesn't exist.
}
jsfiddle.
Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):
var allDivs = document.getElementsByTagName('div');
Any div with an id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
// div with someId exists
}
If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:
<button onclick="
alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
var div = document.createElement('div');
div.id = 'newDiv';
document.body.appendChild(div);
">Add div</button>
Click the Check for div button and you'll get false. Add the div by clicking the Add div button and check again—you'll get true.
is very simple as that
if(document.getElementById("idname")){
//div exists
}
or
if(!document.getElementById("idname")){
// don't exists
}

Categories