Testadmin
Testadmin

Reputation: 2898

change css style using javascript

hi in my php application i want to change the style using javascript

<div id="middle-cnt" class="ad-image-wrapper"><div class="ad-image" style="width: 1000px; height: 450px; top: 0px; left: 131px;"><img height="450" width="1000" src="images/Gallery2/4.jpg"><p class="ad-image-description" style="width: 1000px; bottom: 0px;"><table width="100%"><tbody><tr><td class="image-desc">Stevie III &ndash; 36" long x 24" wide - Oil on Canvas<div style="color: rgb(187, 167, 0); padding-left: 10px; position: absolute; top: 0pt; left: 450px; font-size: 35px; letter-spacing: 6px;">SOLD</div></td></tr></tbody></table></p></div></div>

In the baove code i want to change the div style left:0px ie <div id="middle-cnt" class="ad-image-wrapper" ><div class="ad-image" style="width: 1000px; height: 450px; top: 0px; left: 0px;"><img ..

I am using the script below.

function fnshowgallery(){
var elm=document.getElementById('middle-cnt').childNodes;

    var divElm=elm[0];
    divElm.style.Left='0px';


}

But it's not get the desired result.

Does any one know this?

But i don't know how.

Upvotes: 1

Views: 686

Answers (5)

Linmic
Linmic

Reputation: 791

document.getElementById("middle-cnt").childNodes[0].style.left = "0px";

This should work, if it doesn't, please double-check your DOM structure.

Upvotes: 1

smcphill
smcphill

Reputation: 826

If I evaluate that javascript in my console with that HTML snippet, it works; the "left" styling is changed to 0px.

But, I think you need to have the parent (#middle-cnt) to have position:relative, and your div (.ad-image) with position:absolute. Maybe you have this in your stylesheet...

Might help if you say what browser(s) you have tested with, as well.

Upvotes: 0

Ian Oxley
Ian Oxley

Reputation: 11056

Rather than manipulate the CSS directly with JavaScript it's usually a better approach to only use JavaScript to set the CSS class name and leave all your CSS in your .css files. For example:

/* CSS */
.foo {
    height:450px;
    left:0;
    position:relative; /* or maybe absolute? */
    top:0;
    width:1000px;
}

Then change your JavaScript to something like:

var elm = document.getElementById('middle-cnt').childNodes[0];
if (elm) {
    var cssClass = (elm.className) ? ' foo' : 'foo';
    elm.className += cssClass;
}

Then, if you need to make any more changes to your CSS you shouldn't need to touch the Javascript.

But for the left property to work in your CSS you'll need to set the position property to either relative or absolute.

Upvotes: 0

Kamyar
Kamyar

Reputation: 18797

javascript is a case sensitive language. and it's camel case. So it's not Left but **left. It has to be:

divElm.style.left='0px';  

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117364

The element needs a position-property too, if you want the left-property to have any effect.

Upvotes: 0

Related Questions