Dean Meehan
Dean Meehan

Reputation: 2646

How to use JavaScript or CSS to change a string on a page

How to use JavaScript or CSS to change a string on a page.

I will have around 50 elements which contain tags separated by commas ie

 <a name="tagslist">Skrillex, dubstep, dance</a>

I want to using JavaScript take each of these words and style them differently so that they don't look like they are separated by commas but on different lines. The problem is there can be a variable amount of tag lists on the page.

Is there any way i can achieve this easily?

Upvotes: 1

Views: 125

Answers (5)

NinJoel
NinJoel

Reputation: 29

You would have to have separate anchor tags for each one for them to be styled differently. For line breaks between them, you could put br tags between them.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

First of all, get out of last milennium and use this HTML:

<div id="tagslist">Skrillex, dubstep, dance</div>

Then you can do this:

var elm = document.getElementById('tagslist');
elm.innerHTML = elm.innerHTML.replace(/, /g,'<br />');

You can of course do something more complex, like this:

elm.innerHTML = "<div class='tag'>"+elm.innerHTML.replace(/, /g,"</div><div class='tag'>")+"</div>";

Alternatively, you can use real DOM methods:

var elm = document.getElementById('tagslist'), tags = elm.firstChild.nodeValue.split(", "),
    l = tags.length, i, div;
elm.removeChild(elm.firstChild);
for( i=0; i<l; i++) {
    div = elm.appendChild(document.createElement('div'));
    div.appendChild(document.createTextNode(tags[i]));
    // apply styles, className, etc. to div
}

Upvotes: 2

Peter Lyons
Peter Lyons

Reputation: 145994

Consider using an existing library such as http://ivaynberg.github.com/select2/#tags

Upvotes: 0

w.brian
w.brian

Reputation: 17367

What you want to do is not possible. A more ideal solution would be to have the html be rendered like so:

<span class="tagslist">
    <a href="#">Skrillex</a>
    <a href="#">dubstep</a>
    <a href="#">dance</a>
</span>

This way, you have complete control over the styling using CSS.

Upvotes: -1

Marko Dumic
Marko Dumic

Reputation: 9888

$('a[name="tagslist"]').html(function(_, html){
    var arr = [],
        tags = html.split(/\s*,\s*/);

    for (var i=0; i<tags.length; i++)
        arr.push('<div class="whatever">' + tags[i] + '</div>');

    return arr.join('');
});

Upvotes: 1

Related Questions