Accessing subelement content in javascript

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • P G

    Accessing subelement content in javascript

    Hi all,
    I am a newbie to javascript. Please help me with this....

    I have problem accessing subelement tag content from parent tag in
    javascript. I would like to change the color of text from red to blue.
    In the following code, I am able to set the visibility but not the
    color. Please make any suggestions.

    <HEAD>
    <script language="JavaS cript">
    function setColor(id) {
    if (document.all) { // IE 4+
    document.all[id].style.visibili ty="visible";
    document.all[id].nobr.a.style.c olor = "blue";
    }
    </script>
    </HEAD>
    <BODY>
    <div class="TEST" id="menu1" style="top: 50px" title="Test">
    <nobr><a style="color: 'red'" onClick="setCol or('menu1');" href="#"
    target="content ">test</a></nobr>
    </div>
    </BODY>

    Thanks
    PG
  • Janwillem Borleffs

    #2
    Re: Accessing subelement content in javascript


    "P G" <Pradeep_Gummi@ gmacm.com> schreef in bericht
    news:c4ecce9f.0 310200755.44db1 084@posting.goo gle.com...[color=blue]
    >
    > <script language="JavaS cript">
    > function setColor(id) {
    > if (document.all) { // IE 4+
    > document.all[id].style.visibili ty="visible";
    > document.all[id].nobr.a.style.c olor = "blue";
    > }
    > </script>
    >[/color]

    This could be:

    function setColor(id) {
    if (document.all) { // IE 4+
    document.all[id].style.visibili ty="visible";
    document.all[id].childNodes[0].childNodes[0].style.color = "blue";
    }
    }

    But preferably:

    function setColor(id) {
    if (document.getEl ementById) {
    document.getEle mentById(id).st yle.visibility= "visible";
    document.getEle mentById(id).ch ildNodes[0].childNodes[0].style.color =
    "blue";
    }
    }

    Reason: This way it will work in more browsers then just IE.

    Another way is to pass the object instead of the id. This way your code will
    be shortened:

    function setColor(obj) {
    obj.parentNode. parentNode.styl e.visibility="v isible";
    obj.style.color = "blue";
    }

    .....
    <div class="TEST" id="menu1" style="top: 50px" title="Test">
    <nobr><a style="color:re d" onClick="setCol or(this);" href="#"
    target="content ">test</a></nobr></div>

    BTW, a style property's value doesn't need to be enclosed by quotes. Simply
    'color:red' will do as you can see.

    Last but not least, you can also set the color in the onclick handler:

    <a style="color:re d" onClick="style. color='blue'" href="#"
    target="content ">test</a>


    Goodluck!


    JW



    Comment

    Working...