user893970
user893970

Reputation: 899

How to style with JavaScript

I am trying to use style attribute for JavaScript. But, apparently, I was doing something wrong with it. I am new in JavaScript so a general idea about style attribute for JavaScript would be great. I want to change the place, color and text-decoration etc. of JavaScript elements. I thought that declaring style attribute for div changeMe in HTML will be applied for the JavaScript. Because, JavaScript takes id of it. I wanted to use all of the style attributes that are in the div. Where am I missing? Here is my attempt to do it:

<div id="changeMe" style="position: absolute;text-decoration: none; 
                          color: white;right:43%; top: 90px;">
    <a href="home.php" >Go to homepage</a>
</div>

Javascript:

var testElement = document.getElementById("changeMe");
var text = "aaa".document.getElementById("changeMe");
text.style.textDecoration = "none"; //I changed style here too because first did not       
//work.

check.onfocus= function()
{   
    testElement.innerHTML = text.link("index.php");;
}

Please help me understand the structure.I am stuck.Thanks

Upvotes: 0

Views: 384

Answers (4)

Quentin
Quentin

Reputation: 943108

Your JavaScript will error here:

var text = "aaa".document.getElementById("changeMe");

…since "aaa" is a string and strings do not have a document property. The rest of the script won't execute.

If you fixed that line, then:

text.style.textDecoration = "none";

… would have no effect. The text-decoration is part of the link's style, not the div's.

You need to style the <a> element. If you really want to get to it via JS then you can:

testElement.getElementsByTagName('a')[0]

But you would probably be better off just using a stylesheet:

#changeMe a { text-decoration: none; }

But make sure you do something else to make it clear that the piece of non-underlined text is a link.

Upvotes: 4

Michael Berkowski
Michael Berkowski

Reputation: 270599

Something definitely fishy here.

var text = "aaa".document.getElementById("changeMe");

// Without those "aaa"
var text = document.getElementById("changeMe");

// To change the <a> style inside the 'changeMe' <div>
var alinks = text.getElementsByTagName("a");
for (var i=0; i<alinks.length; i++) {
  alinks[i].style.textDecoration = "none";
}

Here it is in action.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

document.getElementById("changeMe").firstChild.style.textDecoration = "none";

Working Example: http://jsfiddle.net/8Evyq/

Upvotes: 0

Guttsy
Guttsy

Reputation: 2119

You're trying to style the div but you need to apply your text-decoration and color styles to the a tag itself for it to take effect.

All of this can easily be done with cascading style sheets instead, by the way.

Upvotes: 0

Related Questions