Creating a div element in jQuery [duplicate] - javascript

This question already has answers here:
jQuery document.createElement equivalent?
(14 answers)
Closed 5 years ago.
How do I create a div element in jQuery?

As of jQuery 1.4 you can pass attributes to a self-closed element like so:
jQuery('<div>', {
id: 'some-id',
class: 'some-class some-other-class',
title: 'now this div has a title!'
}).appendTo('#mySelector');
Here it is in the Docs
Examples can be found at jQuery 1.4 Released: The 15 New Features you Must Know .

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):
$('#parent').append('<div>hello</div>');
// or
$('<div>hello</div>').appendTo('#parent');
Alternatively, you can use the .html() or .add() as mentioned in a different answer.

Technically $('<div></div>') will 'create' a div element (or more specifically a DIV DOM element) but won't add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append() method or such like).
The manipulation documentation gives you all the various options on how to add new elements.

d = document.createElement('div');
$(d).addClass(classname)
.html(text)
.appendTo($("#myDiv")) //main div
.click(function () {
$(this).remove();
})
.hide()
.slideToggle(300)
.delay(2500)
.slideToggle(300)
.queue(function () {
$(this).remove();
});

div = $("<div>").html("Loading......");
$("body").prepend(div);

$("<div/>").appendTo("div#main");
will append a blank div to <div id="main"></div>

A short way of creating div is
var customDiv = $("<div/>");
Now the custom div can be appended to any other div.

All these worked for me,
HTML part:
<div id="targetDIV" style="border: 1px solid Red">
This text is surrounded by a DIV tag whose id is "targetDIV".
</div>
JavaScript code:
//Way 1: appendTo()
<script type="text/javascript">
$("<div>hello stackoverflow users</div>").appendTo("#targetDIV"); //appendTo: Append at inside bottom
</script>
//Way 2: prependTo()
<script type="text/javascript">
$("<div>Hello, Stack Overflow users</div>").prependTo("#targetDIV"); //prependTo: Append at inside top
</script>
//Way 3: html()
<script type="text/javascript">
$("#targetDIV").html("<div>Hello, Stack Overflow users</div>"); //.html(): Clean HTML inside and append
</script>
//Way 4: append()
<script type="text/javascript">
$("#targetDIV").append("<div>Hello, Stack Overflow users</div>"); //Same as appendTo
</script>

$("<div/>").attr('id','new').appendTo('body');
This will create new div with id "new" into body.

document.createElement('div');

Here's another technique for creating divs with jQuery.
ELEMENT CLONING
Say you have an existing div in your page that you want to clone using jQuery (e.g. to duplicate an input a number of times in a form). You would do so as follows.
$('#clone_button').click(function() {
$('#clone_wrapper div:first')
.clone()
.append('clone')
.appendTo($('#clone_wrapper'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clone_wrapper">
<div>
Div
</div>
</div>
<button id="clone_button">Clone me!</button>

Create an in-memory DIV
$("<div/>");
Add click handlers, styles etc - and finally insert into DOM into a target element selector:
$("<div/>", {
// PROPERTIES HERE
text: "Click me",
id: "example",
"class": "myDiv", // ('class' is still better in quotes)
css: {
color: "red",
fontSize: "3em",
cursor: "pointer"
},
on: {
mouseenter: function() {
console.log("PLEASE... "+ $(this).text());
},
click: function() {
console.log("Hy! My ID is: "+ this.id);
}
},
append: "<i>!!</i>",
appendTo: "body" // Finally, append to any selector
}); // << no need to do anything here as we defined the properties internally.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.

simply if you want to create any HTML tag you can try this
for example
var selectBody = $('body');
var div = $('<div>');
var h1 = $('<h1>');
var p = $('<p>');
if you want to add any element on the flay you can try this
selectBody.append(div);

<div id="foo"></div>
$('#foo').html('<div></div>');

If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:
This is very similar to celoron's answer, but I don't know why they used document.createElement instead of Jquery notation.
$("body").append(function(){
return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
.attr("id","myDivId")
.addClass("myDivClass")
.css("border", "solid")
.append($("<p/>").html("I think, therefore I am."))
.append($("<p/>").html("The die is cast."))
});
//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));
I also think using append() with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.
In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.

alternatively to append()
you can also use appendTo() which has a different syntax:
$("#foo").append("<div>hello world</div>");
$("<div>hello world</div>").appendTo("#foo");

You can create separate tags using the .jquery() method. And create child tags by using the .append() method. As jQuery supports chaining, you can also apply CSS in two ways.
Either specify it in the class or just call .attr():
var lTag = jQuery("<li/>")
.appendTo(".div_class").html(data.productDisplayName);
var aHref = jQuery('<a/>',{
}).appendTo(lTag).attr("href", data.mediumImageURL);
jQuery('<img/>',{
}).appendTo(aHref).attr("src", data.mediumImageURL).attr("alt", data.altText);
Firstly I am appending a list tag to my div tag and inserting JSON data into it. Next, I am creating a child tag of list, provided some attribute. I have assigned the value to a variable, so that it would be easy for me to append it.

I think this is the best way to add a div:
To append a test div to the div element with ID div_id:
$("#div_id").append("div name along with id will come here, for example, test");
Now append HTML to this added test div:
$("#test").append("Your HTML");

I hope that helps code. :) (I use)
function generateParameterForm(fieldName, promptText, valueType) {
//<div class="form-group">
//<label for="yyy" class="control-label">XXX</label>
//<input type="text" class="form-control" id="yyy" name="yyy"/>
//</div>
// Add new div tag
var form = $("<div/>").addClass("form-group");
// Add label for prompt text
var label = $("<label/>").attr("for", fieldName).addClass("control-label").text(promptText);
// Add text field
var input = $("<input/>").attr("type", "text").addClass("form-control").addClass(valueType).attr("id", fieldName).attr("name", fieldName);
// lbl and inp => form
$(form).append(label).append(input);
return $(form);
}

If it is just an empty div, this is sufficient:
$("#foo").append("<div>")
or
$("#foo").append("<div/>")
It gives the same result.

$(HTMLelement) can success it. If you want an epmty div use it as $('<div></div>');. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html() method. For get outerHTML as string you can use is like this :
var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;

You can use .add() to create a new jQuery object and add to the targeted element. Use chaining then to proceed further.
For eg jQueryApi:
$( "div" ).css( "border", "2px solid red" )
.add( "p" )
.css( "background", "yellow" );
div {
width: 60px;
height: 60px;
margin: 10px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

How about this? Here, pElement refers to the element you want this div inside (to be a child of! :).
$("pElement").append("<div></div");
You can easily add anything more to that div in the string - Attributes, Content, you name it. Do note, for attribute values, you need to use the right quotation marks.

I've just made a small jQuery plugin for that.
It follows your syntax:
var myDiv = $.create("div");
DOM node ID can be specified as second parameter:
var secondItem = $.create("div","item2");
Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.
(Answer partially copied from: jQuery document.createElement equivalent?)

Related

Jquery put elements in div

You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());

prev() not returning div element

I'm probably being especially dense about this, but I can't get an element to return using prev(). My basic HTML structure is:
<div>
<table></table>
</div>
<input type="button">
Where when I press the button, I want to get the previous element (the div element). To achieve this my button has a function attached to it with
var nearestDiv = $(this).prev();
When I've checked the contents of nearestDiv in the console it appears to be some kind of JQuery object rather than a HTML div. I've tried popping .val() at the end of .prev() but this comes back empty. How can I get the div element?
Note that my button is generated on the fly and doesn't have anything which identifies it.
you need to use jquery get function, to get a native html object and not the jquery wrapper:
$("input").on("click",function(){
console.log("jquery wrapper:",$(this).prev());
console.log("native html div object:",$(this).prev().get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table></table>
</div>
<input type="button">
If your html structure is same as you provided in the question, it will definitely return the div element. Note that there is no val() method for div element, you need to either use .html() or .text() inorder to get the contents.
$("input[type='button']").click(function () {
var div = $(this).prev();
alert(div.html());
alert(div.text());
});
Fiddle
You need to give .text() or .html() for standard HTML Elements. So your code should be:
var nearestDiv = $(this).prev().html();
var nearestDiv = $(this).prev().text();

Accessing elements inside dynamically created divs with HTML/Javascript

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});

jquery .each() loop

i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});

Create a div containing target div using jQuery

I think that this should be easy, but I'm not able to get it working. I want to target a div or other element using jQuery and then dynamically create a div containing the targeted element, for example:
jQuery ('.myclass')
How can I create a div with the background-color attribute set to white that contains 'myclass' element?
Initially I have: <div class="myclass">Some HTML elements inside</div>
And after executing the jQuery call i want to have: <div style="background-color:#fff"><div class="myclass">Some HTML elements inside</div></div>
I hope that you understand my question...
You can use the wrap function to put a wrapper around the matching elements. I'd prefer to use a class for the background, but you can assign CSS properties directly as well.
$('.myclass').wrap( $('<div></div>').css( 'background-color', '#fff' ) );
or
$('.myclass').wrap( $('<div></div>').addClass('white-background') );
var $myDiv = $('<div>').css('background-color','#fff').append( $('.myclass') );
You can then write this variable to the DOM as you see fit, or do whatever else you need to do.

Categories

Resources