Using html text as selector for CSS with JS? - javascript

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

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>

jQuery .addClass() and .removeClass() only applies to first instance of the element

I have the following code below:
<script type="text/javascript">
var $info = $('#thumb');
enquire.register("(max-width: 480px)", {
match: function() {
$info.removeClass('col-xs-6');
$info.addClass('col-xs-12');
},
unmatch: function() {
$info.removeClass('col-xs-12');
$info.addClass('col-xs-6');
}
}).listen();
</script>
I am using Enquire.js to dynamically add and remove css classes from elements.
The above code works but only for the first '#thumb'. I have about 12 elements which have the thumb id. Anyone know how I can apply it to all elements with the same ID
You have to use a class. ID's are unique so they can only apply it once. If you do: $('.thumb') then you will be fine.
It might be helpful for you to run your source through an html validator, which would help point out that it's not valid to have more than one element with the same id. Which is why it's only updating the first of your 12 elements.
Take a read through this http://css-tricks.com/the-difference-between-id-and-class/ is one quick reference that can hopefully explain the what/why/how of what's going on here.
#xxx is get by id. and you need to make sure this id is unique. If you want to get by class is .xxx for get by class, you will get it in array. So need to to use for-loop to addclass or removeclass

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

Javascript/jQuery .each and syntax issue

I'm having some trouble writing a function to change a background image on a div on document.ready
I haven't made a jsfiddle as i think the problem is just my poor (but improving) jQuery skills. Please let me know if you think one is needed.
Background Info ->
I have a collection of div's with a class of portlet-visible or portlet-hidden, each of these div's will have another class of red-arrow (or a different color, but once i have one color it should be easy to extrapolate). When the page loads i would like a function that can find all divs with a class of portlet-hidden or portlet-visible and see if those have a class of red-arrow. If they do then change the background image src to a different value.
Im really struggling to work this one out, and any help is much appreciated.
My HTML
<div class="portlet-visible red-arrow"></div>
My CSS
div.portlet-visible
{
position:absolute;
top:12px;
right:10px;
background-image:url(../images/red-arrow-up.png);
width:14px;
height:14px;
}
And finally my javascript
$(document).ready(function() {
$(".portlet-hidden" && ".portlet-visible").each(function() {
if ($("this").hasClass(".red-arrow")) {
$(this).css(background-image, url('"url(../images/blue-arrow-up.png)"')
};
});
});
Multiple selectors should be separated by a comma(,) and also css method takes a string or a map. Try this.
$(document).ready(function() {
$(".portlet-hidden, .portlet-visible").each(function() {
if ($(this).hasClass("red-arrow")) {
$(this).css('background-image', "url('../images/blue-arrow-up.png')")
};
});
});
I would have written the selector this way
$(".portlet-hidden, .portlet-visible")
Unless there's a specific reason you want to do this with jQuery you should just use CSS...
div.portlet-visible
{
background-image:url(../images/red-arrow-up.png);
width:14px;
height:14px;
}
div.portlet-visible.red-arrow
{
background-image:url(../images/blue-arrow-up.png);
}
Any div with the class "portlet-visible" is defined in the first block, and any div with the classes "portlet-visible" and "red-arrow" will use the same css, but also apply the new background image.
http://jsfiddle.net/johncmolyneux/gcm5b/
First... Archer's answer is spot on-- what you're trying to do with jQuery can be done with CSS alone.
But if for some reason you do need jQuery, a few things are wrong here.
First, as justtkt said in his answer, your selector is wrong. There is no need (and is syntactically wrong) to use conditional operators like && or || in a jQuery selector. This is simply because there is already conditional syntax built in to CSS, upon which jQuery selectors are directly based.
.this-class.that-class
Selects all elements with both .this-class, and .that-class.
#this-id.that-class
Is a very (possibly overly) specific declaration that select an element (there should only be one ID per page) with both #this-id and .that-class
For more on selectors, please read this very thorough, complete, and educational link http://www.w3.org/TR/selectors/
Additionally and importantly
This line:
$("this").hasClass(".red-arrow")
Is wrong! hasClass does not require a selector (the ".") because it only takes a class. It should be
$("this").hasClass("red-arrow")
Also!!
$(this).css(background-image, url('"url(../images/blue-arrow-up.png)"')
This line has some errors... should be:
$(this).css("background-image", "url(../images/blue-arrow-up.png)")
although I think the following syntax is easier:
css({'background-image' : 'url(../images/blue-arrow-up.png)'})
Your selector is just incorrect. If you want to match things with both classes, it'd be:
$('.portlet-hidden.portlet-visible').each( ...
If you want to match either of the classes:
$('.portlet-hidden, .portlet-visible').each( ...
The expression ".portlet-hidden" && ".portlet-visible" will always evaluate to just ".portlet-visible".
Instead of && two selectors together, use the multiple selector like $(".portlet-hidden, .portlet-visible") or the .add() method to build up your jQuery.
Your current line is actually anding the two strings together, which I believe will return boolean true in Javascript.
if ('$("this").hasClass(".red-arrow")') { <--- this condition is a string here
Should be:
if ($(this).hasClass(".red-arrow")) {
change in selector ".portlet-hidden,.portlet-visible"
change if condition to boolean from string
change in css.
$(".portlet-hidden,.portlet-visible").each(function(){
if ($("this").hasClass("red-arrow")){
$(this).css("background-image", "url('../images/blue-arrow-up.png')");
}
});

jQuery: Modify appended object's CSS

$('#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

Categories

Resources