Search code examples
javascripthtmluserscripts

How do I change an element.style's style? Javascript


Here is my html code I want to change the style of

<img src="linkremoved" style="
    height:45px;
    width:45px;
    margin-right:10px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;">

I can't seem to figure this out. I need this in a userscript form.


Solution

  • With pure javascript it's best to add an id:

    <img id="myImage" src="linkremoved" style="height:45px;width:45px;margin-right:10px;-webkit-border-radius: 50%;-moz-border-radius: 50%;border-radius: 50%;">
    

    and then use:

    document.getElementById('myImage').style.height='50px';
    

    If you can't add an id you'll need:

    /**
     * Get an image by it's src.
     *
     * Returns the first image matching the src
     */
    function getImageBySrc( src ) { 
        var images = document.getElementsByTagName('img');
        for (var i in images) {
            if(images[i].getAttribute('src') == src) {
                return images[i];
            }
        }
        return null;
    }
    
    // useage
    var myImage = getImageBySrc( 'linkremoved' );
    myImage.style.height='50px';