简体   繁体   中英

Editing specific inline <style> 's via javaScript

I have:

<style id=inlinestyle>
    .container {
        height: 0;
    }
    .container li {
        height: 10px;
    }
    .container li a {
                 color: pink;
    }
</style>

I would like to be able to target and edit `.container li a' without losing the other styles i have.

 $('#inlinestyle').html('#poop { color: red }');

This won't work as i will lose everything in there.

Worth mentioning that i'll have an infinity amount of elements being created so inline styles aren't an option.

wouldn't it just be better to target the element you want to modify ?

$('#poop').css('color','red');

And if you'd like to add more than one property to the css of that precise element just do:

$('#poop').css({
    'color' : 'red',
    'font-size' : '16px',
    ......
});
$('#inlinestyle').append('.container li a { /* css here */}');
$('.container li a').css("color", "blue");

Try something like $('#inlinestyle').append(' #poop { color: red; }'); or $('#poop').css('color', 'red');

$('#inlinestyle').append('#poop { color: red }');

You shouldn't edit your original CSS via JS, but add the desired rules the element which is to get styled:

/* What about: */
$( '.container li a' ).css( 'property', 'value' );
/* or */
$( '.container li a' ).css( {
    'property1': 'value1',
    'property2': 'value2'
} );

This should be more or less what you're looking for: http://jsfiddle.net/ZH9JW/2/

The problem with this is that it's a very rigid regular expression; one space more or less, or no newline characters and the regular expression will fail. You can solve this ofcourse, but then you're starting to build a CSS parser. I recommend against using my solution.

Maybe this is something you could use? It's probably faster than $("#poop").css("color", "red"); if you're creating so many elements, but a bit of a hack:

var newStyle = $("<style/>").html(".container li a { color: red }");
$("body").append(newStyle);

This style element should by the way ideally be in the DOM after your original style element, or have more specific CSS.

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