0

Hello I am looking for some working code to create span elements.

My text is simple each word is seperated by space.

I need to create span as follow so that I can lift the code quickly. As mention below each word has unique id as W1, W2, etc.

<p>
  <!-- I need to create span as follow so that -->
  <span id="W1">I</span>  
  <span id="W2">need</span>  
  <span id="W3">to/span>  
  <span id="W4">create</span>  
  <span id="W5">span</span>  
  <span id="W6">as</span>  
  <span id="W7">follow</span>  
  <span id="W8">so</span>  
  <span id="W9">that</span> 
</p>

Thanks.

I have MS expression web and vb studio, any tool I can keep locally and keep creating.

I see this link on web doing something.

2
  • 2
    Smells like a homework... Commented Mar 27, 2013 at 14:47
  • What have you tried? Commented Mar 27, 2013 at 14:56

2 Answers 2

1

Html

<body>
    <p>
    </p>
</body>

Js

<script>
    var sString = "asdf sadfasd f sdfasd fasdfasdfasdf";
    var aString = sString.split(' ');

    for (var i=0;i<aString.length;i++)
    {
        document.getElementsByTagName("p")[0].innerHTML += '<span class="w' + i + '">' + aString[i] + '</span>'
    }
</script>

And always post your code, even if it seems to you foolish and wrong :)

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, Thanks for this code. I was doing this manually using some editor and putting code inside my xhtml file. I need something so that I can see generated HTML code as I showed in the example. Any help will help.
Quick and dirty: prompt("Copy n paste this", document.getElementsByTagName("p")[0].innerHTML); at the end of the above script.
If you user firefox for browsing you can install firebug plugin, really awesome tool for a web developer
1
// You either have a string 
var mysentence = "I need to do my homework";

// or a paragraph
<p id="words">I need to do my homework</p>
// get sentence
var mysentence = document.getElementById('words');


function spanify(sentence) {
  var arrayOfStrings = sentence.split(" "), newString = "";
    for (var i=0; i < arrayOfStrings.length; i++){
        newString += "<span id='W" + i + "'>" + arrayOfStrings[i] + "</span>";
        }
        return newString;
    }

// spanify the sentence
spanify(mysentence);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.