jQuery: Modify appended object's CSS - javascript

$('#foo').css({color:'black'}).append('<div>bar</div>').css({color:'red'});
Given the above, the css() method is applied to foo, but how could you get it to apply to the div that wraps "bar"?
The only way I could think of to do this in the same execution line would be to create a jQuery div object inside of the append(function(){ ... }) and apply the styling there.
Note: I'm trying to avoid inline styling (eg .append('<div style="color:red;">bar</div>')).
Update: I'm actually applying css to foo as well; The example has been updated to reflect this

You can flip the chain around so .css() runs on the appended element by using .appendTo() instead, like this:
$('<div>bar</div>').appendTo('#foo').css({color:'red'});
//or:
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
//or:
$('<div />', { text:'bar', css: {color:'red'} }).appendTo('#foo');

Try this:
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');

$('#foo').append($('<div>bar</div>').css({color:'red'}));

or $something like
$('#foo').append($('<div />').text('bar').css({color:'red'}));

Easiest way is to use appendTo() rather than append():
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
You can find a working sample here: http://jsfiddle.net/YdzGZ/

what about:
$('#foo').append('<div>bar</div>').end().css({color:'red'});

How about you take a step back from the dynamic approach and create a rule or two in css?
#foo { color: black; }
#foo div,
#foo .orViaSomeClassName { color: red; }
No need to monkey about with injected inline styles that way.
And finally yet another approach to getting to the appended div:
$('#foo')
.css('color', 'black') // css on #foo
.append('<div>bar</div>') // appended to #foo
.find('div')
.css('color', 'red'); // css on divs inside #foo

Related

jQuery :hover selector [duplicate]

I need to define a div's background color on :hover with jQuery, but the following doesn't seem to work:
$(".myclass:hover div").css("background-color","red");
How can I get the same result? It's important that it has to be done with jQuery but for some reason it doesn't work. Any suggestions? Thanks!
I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this
$("div.myclass").hover(function() {
$(this).css("background-color","red")
});
You can change your selector as per your need.
As commented by #A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this
$(".myclass, .myclass2").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"red":"transparent")
})
Js Fiddle Demo
You can try this:
$(".myclass").mouseover(function() {
$(this).find(" > div").css("background-color","red");
}).mouseout(function() {
$(this).find(" > div").css("background-color","transparent");
});
DEMO
I know this has an accepted answer but if anyone comes upon this, my solution may help.
I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.
For instance, the css:
.nohover:hover {
color: black !important;
}
Then with jQuery:
$("#elm").addClass("nohover");
With this method, you can override as many DOM elements as you would like without binding tons of onHover events.
Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.
If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.
Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:
$('head').append('<style>.myclass:hover div {background-color : red;}</style>')
If you want to read more on adding CSS with javascript you can check out
one of David Walsh's Blog posts.
Use JQuery Hover to add/remove class or style on Hover:
$( "mah div" ).hover(
function() {
$( this ).css("background-color","red");
}, function() {
$( this ).css("background-color",""); //to remove property set it to ''
}
);
It's too late, however the best example, how to add pseudo element in jQuery style
$(document).ready(function(){
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});
$("a.dummy").hover(function() {
$(this).css("background-color","#0670c9")
}).mouseout(function(){
$(this).css({"background-color":"#003d79",});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<a class="dummy" href="javascript:void()">Just Link</a>

Is this jQuery line of a tutorial necessary?

I'm working with the German book (mediated title) "jQuery the practice book".
In one of the first tutorials the given JS code is like this:
$(document).ready(function()
{
$("#box p").click
(
function()
{
$("#box p").removeClass("green");
$(this)
.addClass("green")
.parent()
.removeClass()
.addClass("boxColor-" + $("#box p").index(this));
}
);
});
the CSS is like this:
<style type ="text/css">
p {
cursor:pointer;
}
.green{
color:#009933;
background-color:#E2FFEC;
cursor:default;
}
</style>
and the HTML is this:
<body>
<div id="box">
<p>Erster Absatz</p>
<p>Zweiter Absatz</p>
<p>Dritter Absatz</p>
</div>
</body>
What makes me stuck is this line of the jQuery script:
.addClass("boxColor-" + $("#box p").index(this));
The Tutorial of the book explains this with a reason like "On which way else we could get the p box related Class?"
But I don't get the point what is happening in that line?
And even if I remove this line, the result I'm seeing keeps being the same.
so, what does happen here? and is it really necessary in any way?
That line is adding a boxColor-N class to the #box element, where N is the index of the <p> you just clicked.
Since there is nothing in the CSS that targets such a class and also no script code that works with it, there are no observable effects.
This line adds a class name. The value that is added is a concatenation of the string boxColor- and the index of the relevant paragraph element.
The index of the element is extracted by using the jQuery index() function.
Regarding your question if it is needed at all really depends on what that class name does. All it's really doing here is adding a class name. If that class name has any other uses such as changing CSS properties then yes, it is needed. In your example, there is no CSS rule for that value - so nothing really changes or happens.
To see this actual doing something, you can add a CSS rule like this:
boxColor-0 {
background:red;
}
boxColor-1 {
background:green;
}
boxColor-2 {
background:blue;
}
With these rules, when you click on a <p> element, it's background color will change.
I don't know if it was an error but as the other explained this will add a class something like "boxColor-" + the index of the element.
But the code
$("#box p").removeClass("green");
$(this)
.addClass("green")
.parent()
.removeClass();
has a closing ; on .removeClass();
In jQuery the Chaining is used to call multiple functions on an element selected but because you are ending the chaining with this line. Otherwise you will add the class to the parent of the <p> tag
.removeClass();
You're not applying the addClass to any object try removing the ; and then use something like
$("#box p").removeClass("green");
$(this)
.addClass("green")
.parent()
.removeClass()
.addClass("boxColor-" + $("#box p").index(this));
Here is an example of how it should work.
JSFiddle

Using html text as selector for CSS with JS?

I'm sure others have asked this but I just cant' find anything that helps me.
Have a look at this code on jsfiddle.
Both Person1 and Person2 have
class="from"
And the CSS selector is .from so it applies to both but I'm trying to achieve that it only applies to Person1 with JavaScript/jQuery.
I've tried numerous things such as
$( "span.from:contains('Person1')" )
with no success. How should I do this?
Help would be much appreciated :)
In your case you can use filter()
$("span.from").filter(function(){ return this.innerHTML == "Person1"; })
to remove the animation of the item remove the from class using removeClass()
$("span.from").filter(function(){
return this.innerHTML == "Person1";
}).removeClass('from');
$( "span.from:contains('Person1')") works just fine. But in css you are still affecting all elements with .from class. After you get the element with Javascript, you should do something with it, like add a new class, and change the css so that the animation runs only on the new class.
$( "span.from:contains('Person1')").addClass('newClass')
CSS:
.newClass{
-webkit-animation: color-change 1s infinite;
...
}
Your code can work
$("span.from:contains('Person1')").text()
See this fiddle
If you are using straight up CSS you should be able to select just the first item using the nth-child selector:
.from:nth-of-type(1) { /* styles here */ }
If you wanted to select the first item via JS you would simply need to use eq() to grab the first item by index. This is chainable, so you could continue to set set CSS on this item similar to this (so in this example I'm adding an extra class on the first .from, and also setting its background color):
$(".from").eq(0).addClass("first-item").css("backgroundColor", "orange");
You can try with .not()
$(".from:not(span:contains('Person2')):eq(0)")

alter divs css with javascript

Can I change style of some div link. Here is what I mean
<div id="somediv">something/div>
Lets say I have css like this :
#somediv a{
color:#000;
}
Now for instance upon some action such as mouse click on any element I want to change somediv a link css to
#somediv a{
color:#00ffff;
}
I know how to select div, by using Document.get.elementById('somediv') Is it possible to select a by using above method or any other?
Thank you
DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..
If you just want to apply a style to a particular element, it's very easy to do:
document.getElementById('whatever').style.color = '#f0f';
If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.
CSS:
#someDiv a {
color: #000;
}
#someDiv.awesome a {
color: #f0f;
}
Javascript:
document.getElementById('someDiv').className = "awesome";
Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.
If you're using jQuery or YUI, there's some good info in question 1079237
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';
assuming the A tag will be the first element inside your DIV
You could use CSS behaviors for this:
For instance:
#somediv a:hover
{
color:#0ff;
}
Otherwise, you may create a dedicated class (used when an element is click for example):
#onclickclass
{
color:#0ff;
}
Then in JavaScript, on onClick event, do:
document.getElementById('somediv').className = 'onclickclass';
And to change the style use
document.getElementById('somediv').className = 'your-css-class';
If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.
As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.

Creating a div element in jQuery [duplicate]

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?)

Categories

Resources