Multiple random id in element - javascript

I have many span element with many ids such as these:
<span id="spn1" class="span-text">hello</span>
<span id="spn2" class="span-text">world</span>
<span id="spn3" class="span-text">12345</span>
It could be 1 or 100 span element. If 100 span was created so the id will be spn100. No problem with that. Now I have problem with javascript code because I hardcoded the ids when the span such as these:
var text = $("#spn1").text() + "\r\n" + $("#spn2").text() + "\r\n" + $("#spn3").text();
The javascript code above was hardcoded so if 100 span was created; my copy function will not worked. How do I solve this problem?
Full code : http://jsfiddle.net/p3h7j4eb/
Thanks in advance

You can use the CSS class as selector and just iterate over that with $.map. Then there's no more need for all those id properties:
var text = $.map($(".span-text"), function(span) {
return $(span).text();
}).join("\r\n");
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="span-text">hello</span>
<span class="span-text">world</span>
<span class="span-text">12345</span>

You can iterate over all elements with you classname, using the 'each' function like this:
var text = '';
$('.span-text').each(function ()
{
text += $(this).text() + '\r\n';
}

Related

Get data-value from element in another file with jQuery

So basically I have some elements with some data-values in a file . I want to dynamically create links to them using those data-values to type the text, href etc.
For example, I have two divs, id'ed firstand second. They have importance values, respectively "most important" and "least important".
I want to create two links to them, with the phrase "This is a link to the most/least important div" using JavaScript/jQuery. Below is a non-working example.
File a.html (ommiting headings and such, ofc):
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
File b.html:
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>
$(`.makelink`).each( function(){
var target = $(this).data('linkto');
$(this).attr('href','b.html#' + target);
var imp = $('b.html #' + target).data('importance');
$(this).html('Link to the ' + imp + ' div');
});
However nothing happens. Any help is appreciated.
Your code seems correct except the selector should be inside quote and the string generated in the html() is not properly formatted:
$('.makelink').each( function(){ // Enclosed the selector with single/double qoute
var target = $(this).data('linkto');
$(this).attr('href','#' + target);
var imp = $('#' + target).data('importance');
$(this).html('Link to the '+ imp + ' div'); // concatenate the string with the variable using +
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>.
every other tag that is not a span tag should be treated as regular text.
The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.
I fail.
is there any other technique that I can try or a workaround?
var problem = ["<h1>","</h1>"];
var red_text = "<span style='color:red'>i am red </span>";
var green_text = "<span style='color:green'>" +
problem[0] +
"i am green" +
problem[1] +
"</span>";
//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";
document.getElementById("demo").innerHTML = red_text + green_text;
document.getElementById("expected").innerHTML = expected_text;
HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/
You need to use HTML entities to escape the < and > in those tags.
For example: "<span style='color:green'><h1>i am green</h1></span>"
See the fiddle: https://jsfiddle.net/ytLftxww/1/
var problem = ["<h1>","<h1>"];
does unescaping the < > work for you?
updated fiddle
You can use &lt for < and & &gt for >.

jQuery .html() function removing text

I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/

Add a span tag inside p after certain amount of characters

Suppose you have this for your HTML:
<div class="contentBox">
<p>I have some content that is good to read</p>
</div>
However you would like to add a span tag after a certain amount of characters, lets say 26 characters, which would be right after the word "that". The result would look like this:
<div class="contentBox">
<p>I have some content that<span> is good to read</span></p>
</div>
It has to be after a certain amount of characters, because the paragraph will change from time to time.
Set the amount of characters after you want to set the span. Get text of the p element. Substring from start until the amount of chars, add the span, continue with the rest and add the closing span
Try:
var after=26;
var html = $(".contentBox p").html();
html = html.substring(0, after) + "<span>" + html.substring(after)+"</span>";
$(".contentBox p").html(html);
DEMO
String.prototype.insertTextAtIndices = function (text) {
return this.replace(/./g, function (char, index) {
return text[index] ? text[index] + char : char;
});
};
//usage
var range = {
25: "<span style='color:red'>",
40: "</span>"
};
document.getElementsByTagName("p")[0].innerHTML = document.getElementsByTagName("p")[0].innerHTML.insertTextAtIndices(range);
http://jsfiddle.net/4zx37Lhm/1/
You can make use of JavaScript's substr method.
function addSpan($elems) {
$elems.each(function() {
var $elem = $(this),
text = $elem.text();
if (text.length <= 25)
return;
var start = text.substr(0, 25), // "I have some content that "
end = text.substr(25, text.length); // "is good to read"
$elem.html(start + '<span>' + end + '</span>');
});
}
addSpan($('.contentBox').find('p'));
span {
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="contentBox">
<p>I have some content that is good to read</p>
</div>
<div class="contentBox">
<p>I have some content that is good to read and this is a much longer string!</p>
</div>
Try this : get first part and second part of the string using substring() and modify text with span element to put it into html of p tag.
Below function will iterate all p under contentBox div, but if you are targeting only one div then you can use it without .each()
$(function(){
$('.contentBox p').each(function(){
var text = $(this).text();
var first = text.substring(0,26);
var second = text.substring(26,text.length);
$(this).html(first + '<span>' + second + '</span>');
});
});
DEMO

How To merge two divs to one div

I have two divs
<div id = "first">some details111</div>
and
<div id = "second">some details222</div>
I want to create:
<div id ="New">some details111 some details222</div>
What is the best and the fast way to do it?
Using jQuery you could do that:
$(document).ready(function(){
$("body").append("<div id='New'></div>");
$("#New").text($("#first").text() + " " +$("#second").text());
});
Some vanilla JS for kicks and giggles:
// grab the content from our two divs
var content1 = document.getElementById('one').innerHTML;
var content2 = document.getElementById('two').innerHTML;
// create our new div, pop the content in it, and give it an id
var combined = document.createElement('div');
combined.innerHTML = content1 + " " + content2; // a little spacing
combined.id = 'new';
// 'container' can be whatever your containing element is
document.getElementById('container').appendChild(combined);
Try the below :
Fiddle Example : http://jsfiddle.net/RYh7U/99/
If you already have a DIV with ID "NEW" then try like below:
$('#New').html($('#first').html() + " " + $('#second').html())
If you want to Create a div and then add the Content then try like below.
$("body").append("<div id ='New'></div>")
$('#New').html($('#first').html() + " " + $('#second').html())
Well, using jQuery you can do by this way:
$("body").append(
$('<div/>')
.attr("id","New")
.html(
$("#first).html() + $("#second").html()
)
);
$("<div></div>").attr("id", "New").html($("#first").html() + $("#second").html()).appendTo($("body"));

Categories