简体   繁体   中英

Change the state of a property from CSS class that has a attribute selector using Javascript

I have this HTML line:

<div id="content" class="slide" data-position="left" ></div>

and this CSS class with this [attribute] selector:

.slide[data-position="left"] {
    display: none;
}

What I'm trying to do is after I click a button the css class will change like this using Javascript

.slide[data-position="left"] {
    display: block;
}

I tried different methods like adding a new class in the HTML line or adding a inline style="display: block;" using Javascript:

$(".slide").attr('data-position', 'left').css({'display':'block'});

that generates

<div id="content" class="slide" data-position="left" style="display: block;"></div>

but the .css() method doesn't help me at all because I want to change/override .slide[data-position="left"]. The inline doesn't change anything in the CSS stylesheet.

I want to know how to change the state of a property for a specific css class that has a certain [attribute] selector.

I tried to google this issue but it seems that nobody has an answer for this.

Any ideas?

Thanks!

Instead of altering the CSS rule directly, you can give the element another class corresponding to another rule:

.slide.active { display: block; }

or, if the attribute has importance still:

.slide.active[data-position="left"] { display: block; }

That rule should go after the existing rule to ensure that a "slide" element that also has the "active" class will be visible.

You'd add the class in JavaScript with

$("#content").addClass("active");

You can achieve this by changing your jQuery selector. At the moment you're using jQuerys attr method to target the data-position attribute and set its value to left. Instead you need to use the same attribute selector you previously used in your CSS declaration: .slide[data-position=left]

What you need to do is change this:

$(".slide").attr('data-position', 'left').css({'display':'block'});

to this:

$(".slide[data-position=left]").css({'display':'block'});

The complete jQuery would look like this:

$("#clickMe").on("click",function(){

    $(".slide[data-position=left]").css({'display':'block'});

});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM