Zheden
Zheden

Reputation: 593

insert text in html tag using javascript

I have following code in cshtml page:

<ul id="menu">
  <li><a href="..." >Link1</a></li>
  <li><a href="..." >Link2</a></li>
</ul>

And I want to change class of a tag when some condition is true. I tried this, but it does not work:

<ul id="menu">
  <li 
    <script> if (..condition..) 
      document.write(" class = \"newclass\"");
    </script>
  ><a href="..." >Link1</a></li>
  <li><a href="..." >Link2</a></li>
</ul>

Could you please suggest the way to do it?

Thanks, Zhenya

Upvotes: 1

Views: 212

Answers (3)

Mirko Cianfarani
Mirko Cianfarani

Reputation: 2103

You have to use document.innerHTML because document.write need the reload page.

<ul id="menu">
                <li  
                    //This is not valid syntax
                    <script> if (..condition..) 
                                document.write(" class = \"newclass\"");
                    </script>
                   ><a href="..." >Link1</a></li>
                <li><a href="..." >Link2</a></li>
            </ul>

Then for you case, I suggest for you

    <ul id="menu">
                    <li id="po"><a href="..." >Link1</a></li>
                    <li ><a href="..." >Link2</a></li>
                </ul>

<script>
document.getElementById("po").className = "newclass";
                        </script>

Upvotes: 0

Jibu K
Jibu K

Reputation: 534

Please give an id to the li

<li id="test"></li> access the <li> by id

$("#test").addClass("classname");

Upvotes: 0

Darren
Darren

Reputation: 70718

Try giving the li an ID as shown below:

 <li id="list"><a href="..." >Link1</a></li>
 <li><a href="..." >Link2</a></li>

Then in your JavaScript try:

if (condition) {
   var element = document.getElementById("list");
   element.className = "newclass";
}

JSFiddle:

http://jsfiddle.net/bVGFP/

Upvotes: 2

Related Questions