2

I was wondering if it was possible to change text dynamically in jQuery.

I want to display this in HTML --

A [dynamic animal name] is my favourite pet.

meaning that

[dynamic animal name]

should be inside an array of words, say

var wordArray = [cat, dog, cow]

How would i go about seperating the paragraphs into one that can be dynamically changed?

I was trying

<p>A <p id="special">[wordArray goes here]</p> is my favourite pet.</p>

but it turns out like this in html:

A cow

is my favourite pet.

meaning it breaks the whole line of words into 2 seperate sentences.

How do i make it go together?

0

5 Answers 5

3

Instead of <p id="special">...</p> use a <span id=special"> ... </span>

spanis an inline element and will not break the view.

Another solution is to use css to make the <p id="special"> element inline:

p#special{
    display:inline;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for providing more than a single answer. that really helped!
2

<span> tag will be the correct one instead of <p> tag for dynamic animal name

Comments

1

try this:

<p>A <span id="special"></span> is my favourite pet.</p>

var animals = ["cat", "dog", "cow"];

$("#special").text(animals[0]);  

Comments

1

Change it to:

<p>A <span id="special">[wordArray goes here]</span> is my favourite pet.</p>

You're using nested <p> tags that is why it's breaking into sentences/paragraphs.

Comments

1

Use a span-tag for the animal:

HTML:

<p>A <span id="special">[wordArray goes here]</span> is my favourite pet.</p>

javascript:

$('#special').text(wordArray[2]);

Also see this example.

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.