开发者

How to style text inserted with innerHTML using JavaScript

开发者 https://www.devze.com 2023-03-24 01:30 出处:网络
I have the following code for a header: <div id=\"title-text\"> The Cuttlefisher Paradise </div>

I have the following code for a header:

<div id="title-text">
    The Cuttlefisher Paradise
</div>
<div id="choices">
    <ul>
        <li id="home"><a href="#">Home</a></li>
        <li id="contact"><a href="#">Contact</a></li>
        <li id="about"><a href="#">About</a></li>
        <!-- 5 more items -->
    </ul>
</div>

I want this to be the header about 10 different web pages. I cannot use <frame> or <iframe> for graphical reasons.

For a开发者_开发百科n example of what I want to do, I am currently using document.getElementById("home").setAttribute("class", "active") to style the active tab, but when the header (the block of code just above) is inserted into a div using innerHTML, document.getElementById does not work (returns null).

What simple method is there to either put the header (without <frame> or <iframe>) on multiple pages or get document.getElementById to find ids inserted with innerHTML?


If you put all that content into a single javascript string and get all the quoting and line breaks right to make it a legal javascript string, then there should be no problem assigning it to innerHTML and the browser will parse all the tags and create the HTML for you.

You can see it work here: http://jsfiddle.net/jfriend00/QmGvF/.

Javascript code called from page ready handler:

var newHTML = '<div id="title-text"> \
    The Cuttlefisher Paradise \
</div> \
<div id="choices"> \
    <ul> \
        <li id="home"><a href="#">Home</a></li> \
        <li id="contact"><a href="#">Contact</a></li> \
        <li id="about"><a href="#">About</a></li> \
        <!-- 5 more items --> \
    </ul> \
</div>';

document.getElementById("top").innerHTML = newHTML;

var home = document.getElementById("home");
home.style.backgroundColor = "#FF0000";
0

精彩评论

暂无评论...
验证码 换一张
取 消