<div id = "board>
<div>{abc</div>
<div>def</div>
<div>ghi}</div>
</div>
I want compare every char inside the div at their position and do something when if found { or }
Im aware that this is possible by wrapping every char within <span></span>
Is there a way to do this without using a span? I will use this for brace matching of my code editor project. this is what i've done using span wrapping, but it is so slow..
$exceedingInlineDiv = $('#board_code_dup > div').eq(x);
if( $exceedingInlineDiv.text() == ''){
var chars = '<span> <br> </span>';
$exceedingInlineDiv.html(chars);
}
else{
var chars = jQuery.map($exceedingInlineDiv.text().split(''), function(c) {
return '<span>' + c + '</span>';
});
$exceedingInlineDiv.html(chars.join(''));
}//else
I'm not sure what you want to do, but maybe you want something like this:
var board = document.getElementById("board"),
divs = board.getElementsByTagName("div"),
texts = [], i = 0;
for (; i < divs.length; i++)
texts.push(divs[i].innerHTML);
// texts => ["{abc", "def", "ghi}"]
Related
Let's say I have an HTML document with the following body:
<style>
.highlighted {
color: red;
background-color: yellow;
}
</style>
<article>My text in an element</article>
I have the challenge to style the i letter from the in word inside the <article> tag with javascript, and I'm required to do it by it's index [8].
So far I can only think of starting with this...
<script>
const article = document.querySelector('article').innerText
console.log(article[8]);
</script>
Expected output:
<article>My text <span class="highlighted">i</span>n an element</article>
// Console
>>>> "i"
...although I've never tried anything like this before, so I'm kinda lost with the following steps.
I supose I need to insert a <span> tag by this index, but I'm not sure how I would set the closing </span> tag or update the DOM.
What would be a good way to achieve this kind of styling?
//get text of article
const article = document.querySelector('article').innerText;
//find index of word 'in'
const index = article.indexOf('in');
//opening and closing tags
const openingTag = '<span style="color:red">'
const closingTag = '</span>'
//insert tags into article
const newHTML
= article.slice(0, index)
+ openingTag + 'in' + closingTag
+ article.slice(index + 2);
document.querySelector('article').innerHTML = newHTML;
This code styles the first occurrence of the word "in" by setting the text color to red. If you want to do something else, change the style attribute of the opening tag.
article.slice(0, index) returns everything before the word "in." In your example, this would evaluate to 'My text '. article.slice(index + 2) returns everything after the word "in" because "in" is 2 letters long. In your example, this would evaluated to ' an element'. When all the strings are concatenated together, the result is 'My text <span style="color:red">in</span> an element'.
const HIGHLIGHT_IDX = 8;
const article = document.querySelector('article').innerText;
const words = article.split(' ');
let highlightCheck = words[0].length;
let wordToHighlight = words[0].length >= HIGHLIGHT_IDX && '0';
let wordIdx = 1;
while (!wordToHighlight) {
highlightCheck += 1 + words[wordIdx].length;
if (highlightCheck >= HIGHLIGHT_IDX) {
wordToHighlight = wordIdx;
} else {
wordIdx += 1;
}
}
words[wordToHighlight] =
`<span class="highlight">${words[wordToHighlight]}</span>`;
document.querySelector('article').innerText = words.join(' ');
Working demo at http://verlager.com/pairing.php uses document.write() but I would prefer to write to a div's ID. I have tried several methods but I can't get the for loop to write to div with id of "textDiv".
<script>
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|";
document.getElementById("textDiv").textContent = res;
}
newly_minted();
</script>
<div id="textDiv" style="background:green; color:fff; display:table; height:10rem; width:40rem; margin:4rem auto; clear:both;"></div>
For original post:
This code replaces textDiv content because of the simple assignment used:
var div = document.getElementById("textDiv");
div.textContent = resort;
var text = div.textContent; //should append not replace!
Try the '+=' operator instead:
var div = document.getElementById("textDiv");
div.textContent += resort;
var text = div.textContent; //should append not replace!
For the updated post:
Declare newly_minted before calling it from a different script element. Hoisting function declarations only applies to the script element in which the function is declared.
Replace $( resort) with resort (and split resort on "|" as in the original). The trailing "|" is not altered in this demonstration:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (let i = 0; i < res.length; i++) {
var resort = res[i] + " ● ";
$( "#textDiv" ).append(resort);
}}
newly_minted();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="textDiv"></div>
Alternatively, without using jQuery, preparing text content first and removing trailing dots:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (var i = 0, text =""; i < res.length; i++) {
text += res[i] + " \u25cf ";
}
text = text.replace(" \u25cf \u25cf ", ""); // remove two trailing dots
document.getElementById("textDiv").textContent = text;
}
newly_minted();
<div id="textDiv"></div>
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
<script>
var chars = 55;
if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>
... The output would be:
This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.
You can try this
var chars = 55;
if ($('#mytext').text().length > chars){
var text = $('#mytext').text(); // div text
var chars_text = text.substring(0, chars); // chars text
var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span
$('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
Note: if you just need to replace the next one dot after chars you can
use '.' instead of /\./g
this way : With JQUERY Substring
<p>
this is test string with jquery . test 1 2 3 4 45 5 . test test test
</p>
<b></b>
<script>
var a = $('p').text();
var _output = '';
var _allow_index = 40;
if (a.length > _allow_index)
{
var x = a.split('.');
for(var i=0; i<x.length; i++)
{ if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
}
else { _output = a; }
$('b').html(_output + '<br>'+a.substr(_output.length,a.length));
</script>
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages.
Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text().
However here is a way for the given case:
var container = $('#mytext');
var length = 55;
var insert = '<br/>';
var text = container.text().trim(); // text() or html()
var dotPosAfterLength = text.indexOf(".", length);
if (dotPosAfterLength != -1) {
container.html(
text.substring(0, dotPosAfterLength+1)
+insert
+text.substring(dotPosAfterLength+1)
);
}
You just need to add this property in CSS.
<div id="mytext">
This is just a example. I need to find a solution.
I will appreciate any help. Thank you.
</div>
<style>
div#mytext{
word-wrap: break-word;
}
</style>
I'd like to select all occurances of <br /> that are within a paragraph <p></p> with a regular expression in JS. Currently I just select all <br /> like this:
var regex = /<br\s*[\/]?>/gi;
But doing this gives me trouble at some point because of what I'm trying to do with the selection. I need a more precise regex since breaks in headlines etc. are irrelevant to me.
If you are wondering about the context of this, I want to replace the <br />'s with two paragraphs with suitable classes to act like a <br /> but to indent the text after the break like this:
function removeEmptyNodes(selector)
{
$(selector).each(function() {
if ($(this).html().replace(/\s| /g, '').length == 0)
$(this).remove();
});
};
function assignIndents()
{
var str = $("#content").html();
var regex = /<br\s*[\/]?>/gi;
$("#content").html(str.replace(regex, "</p><br /><p>"));
$('br').prev('p').addClass('br');
$('br').next('p').addClass('indent');
removeEmptyNodes('#content p');
$('br').next('.scroller').children('p').first().addClass('indent');
$('br').replaceWith('');
removeEmptyNodes('#content p');
};
Edit:
My goal is that I have a paragraph with one or several line breaks. Like this simple case: <p>with some text <br />and another line<p>. I want the text after the line breaks to be indented and to be in a p of their own. So I need to split my original p. I don't want to add in divs or anything else nested in the original paragraphs. I need a bunch of sibling p tags at the end like this: <p class="br">with some text</p><p class="indent">and another line<p>
By which way I replace the <br />'s to split the p's does not matter to me...
Why don't you just find all without a regex?
$('p').each(function(){
var brs = $('br', this); //all <br>s withing this <p>
//do something with brs
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/
UPDATE:
Here is what you want with your new spec:
$('p').each(function(){
var html = this.innerHTML;
var htmlArray = html.split('<br>');
var new_html = htmlArray[0];
for(var i = 1; i < htmlArray.length; i++){
new_html += "<div class='break'>"+htmlArray[i]+"</div>";
}
this.innerHTML = new_html;
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/8/
UPDATE with no nesting:
JS:
$('p').each(function(){
var html = this.innerHTML;
var htmlArray = html.split('<br>');
var new_html = "<p>"+htmlArray[0]+"</p>";
for(var i = 1; i < htmlArray.length; i++){
new_html += "<p class='break'>"+htmlArray[i]+"</p>";
}
$(this).replaceWith(new_html);
});
Fiddle: http://jsfiddle.net/maniator/Ra8ax/11/
Use a Jquery selector instead of regex: $('p br')
Update 2:
$('#content')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
})
.wrap("<p>");
var br = $('#content br');
br.prev('p').addClass('br');
br.next('p').addClass('indent');
br.remove();
http://jsfiddle.net/wWsht/