0

Without using class, how can I apply a simple css rule on a data attribute that gets dynamically added? Here's my current solution with classes, I want to replace this with adding data, and apply the css rule to elements with data attribute 'highlight'. Is this possible? The reason I am doing this is to avoid messing with the underlying DOM data.

$(document).on('mouseover',function (e) {
    e.stopPropagation();
    $(e.target).addClass('highlight');

}).on('mouseout', function (e) {
        e.stopPropagation();
        $(e.target).removeClass('highlight');
});
3
  • so you wanna add data "highlight" and a css rule to the hovered element, and then remove them on mouseout, am I right? Commented Sep 7, 2014 at 4:49
  • @AminJafari yes that is correct, I wasn't sure if this was possible to select elements via data value. Commented Sep 7, 2014 at 4:50
  • But Why dont u use class? Commented Sep 7, 2014 at 4:56

3 Answers 3

2

jQuery

$(document).on('mouseover',function (e) {
    e.stopPropagation();
    $(e.target).attr('data-highlight', 'init');

}).on('mouseout', function (e) {
    e.stopPropagation();
    $(e.target).removeAttr('data-highlight');
});

CSS

[data-highlight] {
    background: yellow;
}

jsFiddle Demo.

Sign up to request clarification or add additional context in comments.

2 Comments

can you also use that selector in jquery? $('*[data-highlight]) ?
@user299709 Yes, all css selectors exists in jQuery.
1

if you want what I said in the comments then this is the correct approach:

$(document).on('mouseover',function (e) {
    e.stopPropagation();
    $(e.target).data('highlight',true).css('background-color','#F00'); //the background is an example

}).on('mouseout', function (e) {
        e.stopPropagation();
        $(e.target).data('highlight',false).css('background-color','#CCC');
});

Although if you wanna select an element by its data attribute, then you may wanna take a look at this. the code below gets all the <a> with the data attribute highlight set as true:

$(document).on('mouseover',$('a').filter(function(){return $(this).data('highlight');}), function(){

}).on('mouseout', $('a').filter(function(){return $(this).data('highlight');}), function(){

});

Comments

0

I believe this is what is needed.

$(e.target).addClass('highlight').css('display', 'block');

or could be

$(e.target).data('class','highlight').css('display', 'block');

just because you mentioned to add a data attribute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.