I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!
document.getElementById("Combo Style").onclick = function() {
document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5";
}
You can use cssText property but it will change the styling for the element completely
Style cssText Property
document.getElementById("myP").style.cssText = "background-color:pink;font-size:55px;border:2px dashed green;color:white;"
This will overwrite the existing css styling for that element , so make sure you included every needed property.
To achieve your expected result use setAttribute
HTML:
<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>
JS:
document.getElementById("Combo Style").onclick = function() {
document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");
}
http://codepen.io/nagasai/pen/AXVWwO
You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -
var element=document.getElementById("More Text");
element.style.fontSize="20px";
element.style.color="red";
element.style.background="blue";
You can also use cssText property, like -
document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'
This will insert an inline style tag in the element with the csstext property.
I would like to use jQuery to insert an html element inside another element and at a particular position.
I've found a way I can do it in Javascript but was wondering if there's a shorter 'one line of code' way of doing it in jQuery.
var container = document.getElementById("container");
container.insertBefore( html, container.children[0] );
Many thanks in advance
Use the selector for the n-th child of a given kind and the before method (assuming your new content comes in html) :
$("#container > div:nth-of-type(42)").before(html);
If you want to insert a new element as the first or last child of a container, there is another api option:
$("#container").append( html );
$("#container").prepend( html );
(For the sake of completeness, append / prepend are the links into the jQuery API docs)
If you want to add an element inside an other with jquery, you have to do like this :
$('#container').append(html);
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
}
}
});
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());
});
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?)