I know this been posted here: how to split the string using jquery or javascript
but in my case have multiple strings. It's working in a single line of string but if it's in a multiple lines it repeats the day after year. and for some reason it display's only the first 'li' value. Is it possible to display it this way:
<ul>
<li>
<div class="date">
<p class='day'>23</p>
<p class='month'>05</p>
<p class='year'>2013</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>25</p>
<p class='month'>07</p>
<p class='year'>2014</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>01</p>
<p class='month'>05</p>
<p class='year'>2014</p>
</div>
</li>
</ul>
here is my code:
html
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>
css:
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
script:
var data =$('.date').text();
var arr = data.split('-');
$(".date").html("<p class='day'>"+arr[0]+"</p>"+"<p class='month'>"+arr[1]+"</p>"+"<p cass='year'>"+arr[2]+"</p>");
jsfiddle:
demo
thanks Bon
You are getting the text from the first element, and changes all elements to contain the code for that. You need to loop through the elements and convert the content in each one.
You can use a callback function in the html method to do that, it will get the original HTML code from each element, and you return the new HTML code for that element:
$(".date").html(function(i, h) {
var arr = h.split('-');
return "<p class='day'>"+arr[0]+"</p><p class='month'>"+arr[1]+"</p><p class='year'>"+arr[2]+"</p>";
});
Demo: http://jsfiddle.net/Guffa/815c95jn/1/
(Note the difference in function, as this will get the HTML code in each element instead of the text. As long as there is no actual HTML markup in the elements, like in your example, there is no difference in the result.)
An alternative to splitting the text is to use replace:
$(".date").html(function(i, h) {
return "<p class='day'>" + h.replace("-", "</p><p class='month'>").replace("-", "</p><p class='year'>") + "</p>";
});
You only selected one .date, but you have to iterate over all of them, e.g. using $.each():
$(".date").each(function () {
var data = $(this).text();
var arr = data.split('-');
$(this).html("<p class='day'>" + arr[0] + "</p>" +
"<p class='month'>" + arr[1] + "</p>" + "<p class='year'>" + arr[2] + "</p>");
});
Adjusted Fiddle, and for reference: http://api.jquery.com/each/
Since the title asks about how to completed this with jQuery or Javascript (assuming vanilla JS) let me give a quick example of how this might be done without the need for jQuery:
var dates = document.querySelectorAll('.date');
var dateClasses = ['day', 'month', 'year'];
Array.prototype.forEach.call(dates, function(date){
var dateString = date.innerHTML;
var dateStringArray = dateString.split('-');
var content = "";
for(var i = 0; i < dateStringArray.length; i++){
var newDate = document.createElement('p');
newDate.classList.add(dateClasses[i]);
newDate.innerHTML = dateStringArray[i];
content += newDate.outerHTML;
}
date.innerHTML = content;
});
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>
Related
I would like to insert HTML code to make a "list". I've seen examples of innerHTML but that just replaces the existing code. How can I add more code without replacing the current code?
var addTo = document.querySelector(".activePage")[0];
var addHTML = '
<div id="item1">
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</div>'
addTo.innerHTML(addHTML)'
<nav class="activePage"><nav>
Use insertAdjacentHtml. Docs - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML.
var addTo = document.querySelector(".activePage");
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>
addTo.insertAdjacentHtml(addHTML, 'beforeEnd')
'beforeEnd' means it will add right before the end of the element(inside the element).
You have to append to the HTML inside the nav tag instead of replace it with a new value.
var addTo = document.querySelector(".activePage");
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>';
addTo.innerHTML += addHTML;
<nav class="activePage">
<nav>
Add your HTML to the existing HTML inside of the target element using +=.
function addNew() {
var addTo = document.querySelectorAll(".activePage")[0];
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>'
addTo.innerHTML += addHTML
}
<nav class="activePage">
<button onclick="addNew()">add</button>
<nav>
I believe what you're after is the append feature.
https://api.jquery.com/append/
or
https://www.w3schools.com/jsref/met_node_appendchild.asp
Below is a jquery example. I have used this example as i think it's easier to understand what's going on at first glance
example:
$(".your_div").append(html_load());
function html_load() {
return '<li class="list"> list item </li>'
}
This will result in the below:
<div class="your_div">
<li>start</li>
</div>
being updated to:
<div class="your_div">
<li>start</li>
<li class="list"> list item </li>
</div>
I'm trying to create a line break in my showPhoto() function but nothing seems to work. I've tried using br, tried using html() but still didn't budge. The comment in my Javascript code shows the return line i am talking about.
If there any better methods to achieve my desired result??
Any help is appreciated.
Thanks
JS :
function photo(theCountry, theLocation, theCamera, theDescription) {
this.photoCountry = theCountry;
this.photoLocation = theLocation;
this.photoCamera = theCamera;
this.photoDescription = theDescription;
this.showPhoto = function() {
// How do i create line breaks here?? I want each sub heading on a different line.
return 'Country: ' + this.photoCountry + ' Location: ' + this.photoLocation + ' Shot With: ' + this.photoCamera + ' Description: ' + this.photoDescription;
}
}
var photo1 = new photo('New Zealand', 'Queenstown', 'Canon 550D', '...');
var photo2 = new photo('Singapore', 'Skyline', 'Canon 550D', '....');
var photo3 = new photo('Canada', 'Vancouver', 'Canon 550D', '...');
var photo4 = new photo('New Zealand', 'Lake Wanaka', 'Canon 550D', '....');
var photo5 = new photo('Australia', 'Mornington Peninsula', 'Canon 550D', '...')
$('.photoImg').click(function() {
var sourceImage = document.createElement('img');
sourceImage.className = 'photoFocus';
sourceImage.src = this.src;
var theDiv = document.getElementById('selectionContainer');
$(theDiv).html(sourceImage);
var textDiv = document.createElement('div');
textDiv.setAttribute('id', 'textContainer');
var textNodeArray = {'photo1': photo1, 'photo2': photo2, 'photo3': photo3, 'photo4': photo4, 'photo5': photo5}
$('#textContainer').html(document.createTextNode(textNodeArray[this.id].showPhoto()));
});
You can Use CSS like
li{
float:left;
padding:5px; /* or anything you need */
margin-top:10px; /* or anything you need */
}
This your HTML
<ul>
<li> <img src='images/newzealand.jpg' class='photoImg' id='photo1'> </li>
<li> <img src='images/singapore.jpg' class='photoImg' id='photo2'> </li>
<li> <img src='images/vancouver.jpg' class='photoImg' id='photo3'> </li>
<li> <img src='images/newzealand2.jpg' class='photoImg' id='photo4'> </li>
<li> <img src='images/mornington.jpg' class='photoImg' id='photo5'> </li>
<li> <img src='images/newzealand1.jpg' class='photoImg' id='photo6'> </li>
<li> <img src='images/newzealand3.jpg' class='photoImg' id='photo7'> </li>
</ul>
You can't really add a line break inside a TextNode (created by createTextNode).
See this :
Javascript, trying to add linebreak inside create text node method
A solution could be to have your showPhoto function return a list of the text for the different lines, and create several TextNodes, separated by "br" nodes.
Something in the spirit of :
this.showPhoto = function() {
// How do i create line breaks here?? I want each sub heading on a different line.
return ["Country : " + this.photoCountry,
"Location : " + this.photoLocation, ...]
}
Then (probably using an iterator on lines, any maybe wraping DOM elements to please jquery)
var lines = textNodeArray[this.id].showPhoto())
$('#textContainer').append(document.createTextNode(lines[0]);
$('#textContainer').append(document.createElement("br"));
$('#textContainer').append(document.createTextNode(lines[1]);
..
Use the <br> tag in your output (which you will treat as an HTML fragment):
return 'Country: ' + this.photoCountry + '<br>Location: ' + this.photoLocation + '<br>Shot With: ' + this.photoCamera + '<br>Description: ' + this.photoDescription;
As you're using jQuery, you can directly output the the HTML returned by your showPhoto method:
$('#textContainer').html(textNodeArray[this.id].showPhoto());
jQUery will parse the HTML string and take care of the actual DOM node creation for you.
I have the following structure:
<span class="h1">Color green</span>
<div class="swatchesContainer">
<img title="green" src="/"/>
<img title="blue" src="/"/>
</div>
Now I want to change the color in the in the span to the color which is stated in the titleof the image. (No I am not able to add a class with the color name)
I have tried te following code:
var product_name = jQuery(".h1").text();
jQuery(".swatchesContainer img").click(function(){
var selected_color = jQuery(this).attr('title');
var string;
console.log("String before: " + product_name);
jQuery('.swatchesContainer img').each(function(){
string = product_name.replace(jQuery(this).attr('title').trim(),' ');
console.log(jQuery(this).attr('title'));
})
console.log("String after: " + string);
jQuery(".h1").text(string + " " +selected_color);
});
I'm fetching all the title attributes from te images and replace them from te text in the same foreach function
But the new color keeps appending after the existing color
JSFiddle
There is a flaw in your logic. Inside the loop you are repeatedly overwriting the string variable:
string = product_name.replace(...)
At the end of loop you will have "Color green".replace("blue", " ") -> "Color green".
Change these lines:
var string;
// ...
string = product_name.replace(jQuery(this).attr('title').trim(),' ');
To these:
var string = product_name;
// ...
string = string.replace(jQuery(this).attr('title').trim(),' ');
Updated Fiddle
Having said all that, I would rather change the markup to this:
<span class="h1">Color <span class="chosen-color">green</span></span>
<div class="swatchesContainer">
<img title="green">
<img title="blue">
</div>
And overwrite the contents of .chosen-color instead of get/match/replace the entire text inside .h1. Your jQuery code will be reduced to one line.
Another approach would be:
var span = $('.h1');
$('.swatchesContainer img').on('click', function() {
var txtArr = span.text().split(' ');
txtArr[1] = this.title;
span.text( txtArr.join(' ') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="h1">Color green</span>
<div class="swatchesContainer">
<img title="green" src="/"/>
<img title="blue" src="/"/>
</div>
I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>
How do I output javascript into the html below. I've been trying to get anything to display, but the only thing that displays is "object,object"
<h2>title</h2>
<ul>
<li>rating</li>
<li>year</li>
<li>length</li>
<li>comedy</li>
<li>main characters</li>
</ul>
Thank you for you help everyone. I really appreciate it.
Pure JavaScript can be a little nasty on the eyes sometimes:
for (var i = 0; i < movieList.length; i++) {
document.body.appendChild(document.createElement('h2')).appendChild(document.createTextNode('title: ' + movieList[i].title));
var cUL = document.body.appendChild(document.createElement('ul'));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].rating));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].year));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].length));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode(movieList[i].isComedy));
cUL.appendChild(document.createElement('li')).appendChild(document.createTextNode('main characters: ' + movieList[i].mainCharacters.join(", ")));
}
Demo here.
Here is your HTML:
<body id="thebody">
<h2>title: Goodfellas</h2>
<ul>
<li>rating: R</li>
<li>year: 1990</li>
<li>length: 3.25</li>
<li>comedy</li>
<li>main characters: James Conway, Henry Hill</li>
</ul>
</body>
HEre is your JS
var list = document.createElement("ul");
for (var key in movieList) {
var title = document.createElement("li");
var titleText = document.createTextNode("title: " + movieList[key].title);
title.appendChild(titleText);
list.appendChild(title);
}
var _body = document.getElementById('thebody');
_body.appendChild(list);
Here is the demo of course do this with every property
make your list and items into a template and cloning using jquery so you can insert the data into the elements. It's a relatively simple pattern to produce.
var divContainer = $('#divContainer');
for ( var i = 0; i < array.length; i += 1 )
divContainer.append
(
$('<ul></ul>').append
(
$('<li><li>').innerHtml(" prop Name " + array[i].propName)
)
);
Since it seems you are just getting started, here is a good little reference to get you started in the right direction. I wouldn't rely on a book chapter by chapter to get where you want to go. It's tedious and unrealistic. Make a goal and do some research, take it a reasonable and applicable problem at a time instead of tackling the whole of the language right off.
Here's a quick solution if you happen to be using jQuery:
Example (jsFiddle)
// loop through the movie list.
$.each(movieList, function() {
$('<h2>'+this.title+'<h2>').appendTo('#movies');
$('<ul>').appendTo('#movies');
$('<li>'+this.rating+'</li><li>'+this.year+'</li><li>'+this.length+'</li><li>'+this.isComedy+'</li>').appendTo('#movies');
// open the main characters list item.
var charLi = '<li>main characters: ';
$.each(this.mainCharacters, function() {
charLi += this + ', ';
});
// remove the extra comma and space.
charLi = charLi.substring(0, charLi.length - 2);
// close the list item.
charLi += '</li>';
$(charLi).appendTo('#movies');
$('</ul>').appendTo('#movies');
});