This question already has answers here:
How to wrap each word of an element in a span tag?
(10 answers)
Closed 6 years ago.
for example i have some HTML elements like below
<p> apple,banana,oranger</p>
and i'd like to use the javascript to make it like
<p>apple</p> <p>banana</p> <p>orange</p>
How may i achieve this?
UPDATE 1:
I am using other methods to do my task due to some reaseon and it looks as like below
var node = document.getElementById('discovereedKeywords');
node.innerHTML = node.innerHTML.replace(/,/g, '<p class="tag-item">');
and in reality those <p> tags are actually generate by a for loop, but my method only change the first node it found therefore i tried
Consider the html looks like this
<p class="discovereedKeywords"> apple,banana,oranger</p>
<p class="discovereedKeywords"> apple,oranger,oranger</p>
<p class="discovereedKeywords"> kiwi,melon,pinapple</p>
Javascript
for (var i=0; i <data.result.data.length; i++){
var node[i] = document.getElementByClassName('discovereedKeywords');
node[i].innerHTML = node.innerHTML.replace(/,/g, '<p class="tag-item">');
}
}
but this those work, why?
Use .split to split the string in array. .join the array in string by concatenating </p></p> in between items. Wrap the string in <p>
$('p').get(0).outerHTML = ('<p>' + $('p').text().split(',').join('</p><p>') + '</p>');
p {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>apple,banana,oranger</p>
OR using Array#map without jQuery
var elem = document.getElementById('demo');
elem.outerHTML = elem.textContent.split(',').map(function(el) {
return '<p>' + el + '</p>';
}).join('');
p {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id='demo'>apple,banana,oranger</p>
You can do something like this
$('#p').html(function(i, v) {
return '<p class="discovereedKeywords">' + v.split(',').join('</p><p class="discovereedKeywords">') + '</p>'; // update the html content
})
.children() // get children p
.unwrap(); // unwrap the parent p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p">apple,banana,oranger</p>
Or use replace() here
$('#p').html(function(i, v) {
return v.replace(/([^,]+)(?:,|$)/g, '<p class="discovereedKeywords">$1</p>')
})
.children() // get children p
.unwrap(); // unwrap the parent p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p">apple,banana,oranger</p>
Related
Any idea how make it with link? I try but nothing
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
$(".wd-entities-title").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
http://jsfiddle.net/nd46b23L/
The text you want to separate is inside an <a> tag - you should include that in your query or else the first space you'll encounter is the space in the <a> tag.
$(".wd-entities-title a").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
Slightly less verbose approach using html(function) which will iterate over all instances of matching selector <a> exposing the current html for each instance
Then use replace() to insert the break at first space and return the modified string
$(".wd-entities-title a").html((i, curr) => curr.trim().replace(' ', ' <br/>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
I am in client side context.
I have this html:
<p>Text text \n other text </p>
I want to match only \n element inside paragraph, and replace only this with "br" tag.
I want to do this only inside tag "p" and for all match.
I supposed to use regex in javascript.
Thanks and sorry for my bad english.
Use html() method with callback and inside callback replace text using String#replace method.
$('p').html(function(i, htm) {
return htm.replace(/\\n/g, '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text text \n other text</p>
UPDATE 1 : If it's a string then use String#replace method.
console.log(
'<p>Text text \n other text</p>'.replace(/\n/g, '<br>')
)
UPDATE 2 : If the string contains other tag element and you just want to update the p tag then do something like.
var str = '<p>Text text \n other text</p>';
console.log(
// create a temporary div eleemnt
$('<div>', {
// set html content from string
html: str
})
// get all p tags
.find('p')
// iterate and replace \n
.html(function(i, htm) {
// replace \n with br tag
return htm.replace(/\n/g, '<br>')
})
// back to the temp div
.end()
// get it's updated html content
.html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE 3 : With pure JavaScript by generating a temporary DOM element.
var str = '<p>Text text \n other text</p>';
// create a temporary div element
var div = document.createElement('div');
// set html content form string
div.innerHTML = str;
// get all p tags and convert into Array using Array.from
// for older browser use [].sclice.call instead
Array.from(div.getElementsByTagName('p'))
// iterate over p tags
.forEach(function(el) {
// update the html content
el.innerHTML = el.innerHTML.replace(/\n/g, '<br>')
});
// get updated html content
console.log(div.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use a for loop with getElementsByTagName:
for(i = 0; i < window.document.getElementsByTagName("p").length; i++){
window.document.getElementsByTagName("p")[i].innerHTML = window.document.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
If this is inside a string and not inside the HTML, you can add it to a <div> element while handling it like this:
var myString = "<p>Text text \n other text </p>";
var div = document.createElement("div");
div.innerHTML = myString;
for(i = 0; i < div.getElementsByTagName("p").length; i++){
div.getElementsByTagName("p")[i].innerHTML = div.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
myString = div.innerHTML;
I've searched but cannot find a solution to increment the font color (eg. lightness +10%) for each of 3 or 4 words in a title. The font color will be initially set in SCSS with a color var.
Example Title:
Here Is My New Title
In this example, lets say the title was 'dark blue'.. the words would be:
Here = darker blue
Is = navy blue
My = medium blue
New Title = light blue
There is a similar post here: JavaScript Text Color Change To Each Word In Array but this is searching for keywords in an array, not each word of a string.
I've also come across basic CSS/HTML only solutions like this, which won't work: HTML: Changing colors of specific words in a string of text
NOTE:
I will be returning the title (string) in a php variable - in case there is a solution in PHP.
GOAL: I need to increment the font color (or even wrap consecutive words in spans and increment the SCSS var) for each word in a string.. open to suggestions.
UPDATE
I've added a jsfiddle link (http://jsfiddle.net/revive/xyy04u7d/) to show the JS implementation, thanks to Tushar, with some changes to include ampersands in the regex.
Here is the PHP implementation:
<?php
$title = "SIMPLE TITLE & WITHOUT COLORS";
$words = preg_split('/\s+(?!&)/', $title);
?>
<h3 class="colors blue">
<?php foreach($words as $word):?>
<span><?php echo $word; ?></span>
<?php endforeach; ?>
</h3>
You can wrap the each word in separate span or any other element and then can be styled differently using the CSS nth-child property.
Using this approach, you don't have to create separate classes, and it'll work for any number of words in string.
var str = 'Split the Text by one or more spaces. Join them to make them wrap in span elements. Then use CSS nthChild Properties :)';
str = '<span>' + str.split(/\s+/).join('</span> <span>') + '</span>';
$(document.body).append(str);
span:nth-child(4n) {
color: red;
}
span:nth-child(4n + 1) {
color: green;
}
span:nth-child(4n + 2) {
color: blue;
}
span:nth-child(4n + 3) {
color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
You can also use regex as follow:
$("h1").html(function(i, oldHtml) {
return oldHtml.replace(/(\S+)/g, '<span>$1</span>');
});
span:nth-child(4n) {
color: red;
}
span:nth-child(4n + 1) {
color: green;
}
span:nth-child(4n + 2) {
color: blue;
}
span:nth-child(4n + 3) {
color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<h1> Hello World! Have a Great Day! </h1>
Here is a demo that splits the words based on spaces, wraps each word in a span with a class name. You can style the elements however you like using the class name.
var str = "Here Is My New Title which may well be way too longer than I have actually provided";
var res = "";
str.split(/\s+/).forEach(function(str, idx) {
//Would only work with the string in question
//res += "<span class='color-"+(idx+1)+"'>" + str + " </span>";
//Would work with any amount of words in a string, applying the same set of classes every 5 words.
res += "<span class='color-" + (idx % 5) + "'>" + str + " </span>";
});
$("body").append(res);
.color-0 {
color: violet;
}
.color-1 {
color: indigo;
}
.color-2 {
color: blue;
}
.color-3 {
color: green;
}
.color-4 {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
here is similar answer
change perticular text
first = str.substring(0,till);
second = str.substring(till,last);
//Print data
$(this).html("<span style=color:"+setting.color+">"+first+"</span>"+ second);
Download Plugin : string_color
I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>
Let's say I have the following HTML code
<div class="answers">
He<b>y</b> <span class='doesntmatter'>eve</span>ryone
</div>
And I have the following array:
['correct','correct','incorrect','correct','correct','correct','incorrect','incorrect','correct','correct','incorrect']
I want to transform this piece of HTML code, and add a span to each letter with the class in the array (I'll explain)
So, I want to transform the letter H to say <span class='correct'>H</span>
e to say: <span class='correct'>e</span>
y to say: <span class='incorrect'>y</span>
e to say: <span class='correct'>e</span>
And so on. I want to make sure to keep the original HTML, <br> tags, <p> tags and the such. I can't use jQuery(element).text() for this reason (since it breaks the tags).
Anyone has an idea how I would do this? It's much appreciated.
var arr = ['correct','correct','incorrect','correct','correct','correct','incorrect','incorrect','correct','correct','incorrect'],
answer = document.getElementsByClassName("answers")[0],
rex = /(?=\w|<)(?=[^>]*(?:<|$))/,
i = 0, class;
answer.innerHTML = answer.innerHTML.split(rex).map(function(p) {
if (p.indexOf('>')) return p;
class = arr[i++] || 'notDefined';
return '<span class="' + class + '">' + p + '</span>';
}).join('');
Non-word characters are not wrapped. If the text contains html-entities (e.g ) there will be some extra effort.
How about this:
http://jsfiddle.net/bn777pky/
The jQuery needs refined but it's not my strong suit.
HTML
<div class="numbers">123456789</div>
CSS
.correct {
color: red
}
.incorrect {
color: blue;
}
Jquery
$(".numbers").each(function (index) {
var characters = $(this).text().split("");
$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
$this.append("<span>" + el + "</span");
});
$("span").each( function (index) {
index += 1;
if(index % 3 == 0) {
$(this).addClass("incorrect");
}
else {
$(this).addClass("correct");
}
});
});