getting the innerHTML after finding the innerText - javascript

I have a RegEx to find the part of the text I want :
var re = RegExp("(?:^\\W*|(" + motBefore.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")\\W+)" + motErreur.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?:\\W+(" + motAfter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")|\\W*$)", "g");
var resultMatch = document.getElementById('edth_corps').innerText.match(re);
Like this I can retrieve back the part of the text I need to modify with the punctuation. The trouble I get from here is to retrieve the innerHtml of this so I can get if in this part there is tag around the "motErreur".
I need to have to innerHTML because the purpose of my function is to wrap a span around the motErreur but this :
var reInner = resultMatch[0].replace(new RegExp("\\b" + motErreur + "\\b", "gi"), '<span id="'+nbId+'" class="erreurOrthographe" oncontextmenu="rightClickMustWork(event, this);return false">' + motErreur + '</span>');
document.getElementById('edth_corps').innerHTML = document.getElementById('edth_corps').innerHTML.replace(resultMatch, reInner);
does not work since between the innerText and the innerHTML it is possible to have tag already wrap around the part of text I get.
Example :
Input => this, tset, that; result : work fine because innerHTML and innerText are the same (no tag to mess up the search)
Input2 => this, <em>tset</em>, that; result : does not work since the innerText and the innerHTML are not the same (resultMatch is not the same as variable as what it is in the last replace).
I actually have no idea how to link these two thing correctly in the simplest way possible.
Configuration : javascript, compiled in quirks mode (only utility on IE, i don't care about other browser).

The trouble I get is that if there is already a span around motErreur
Assuming the innerHTML you get can only have a tag around your mot erreur you could check if there's a span this way :
if (theInnerHtml.firstChild) {
// It has at least one
var yourSpan = document.createElement('span');
// you set the innerHTML of yourSpan with the innerHTML of the child
// Ex <p> blablabla <em>motErreur</em> blabla </p>
// yourSpan will be "<span>motErreur</span>"
yourSpan.innerHTML = theInnerHtml.firstChild.innerHTML;
// you empty the innerHTML of your the child
// It will be <p> blablabla <em></em> blabla </p>
theInnerHTML.firstChil.innerHTML = "";
// Then you append your span to the firstChild
// It will be <p> blablabla <em><span>motErreur</span></em> blabla </p>
theInnerHTML.firstChild.appendChild(yourSpan):
}
This therefore implies that your innerHTML will only have 1 possible child, and that this child will be wrapping your motErreur

Related

How to give two css class name together ,second one is removed after page is rendered?

var cssClass ;
cssClass = "fa-leaf green-icon";
var textValue = '<span class=' + cssClass + '>' + nodeName + '</span>';
later I've used this text value to in column header in grid panel in Extjs 6.
When page is played green-icon class is removed from class, it becomes like this
<span class="fa-leaf" green-icon>name</span>, but it should have been like this:
<span class="fa-leaf green-icon">name</span>
Your code suggest that you start off with '<span class=fa-leaf green-icon>name</span>, since you do not include the " quotes when creating the html string.
Try that first. When constructing HTML with string concatenation, you have to write the quotes around attributes yourself.
The browser can interpret attributes not wrapped between ", but as you see that leads to issues when the value contains spaces, since <span class="fa-leaf" green-icon> basically means the span has a class attribute with the value fa-leaf and a green-icon attribute without a value that the browser will ignore.
So try: var textValue = '<span class="' + cssClass + '">' + nodeName + '</span>'; first and see how extjs reacts to it.

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 >.

Javascript - Getting the first character of my string - error

can you tell me why the console says that it is not a function?
var firstAuthorName = document.getElementById("firstAuthorName");
var firstCharacter = console.log(firstAuthorName.slice(0,1));
then I get the text by this:
div.innerHTML += firstCharacter.value + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";
So the console says: "Uncaught TypeError: firstAuthorName.slice is not a function"
You need to access the contents of the HTML element and get the first character of that. You are attempting to get the first letter from the HTML DOM object itself, not the content of the object.
There are 3 standard ways to extract content of an element and which
you use depends on the kind of element you have and the kind of
content it contains:
1a. value : If the element is a form-field (radio button, checkbox,
text box, etc.) value is always used to get the value being held
in form-field.
1b. value is also used to obtain the value of an HTML element's attribute as in:
var src = document.querySelector("img").attributes[0].value;
console.log("The value of the \"src\" attribute of the image is: " + src);
<img src="images/someImage.jpg">
For non-form field elements, you can use textContent or innerHTML.
textContent just gets the characters that are the contents of an element (minus any HTML). If the element only contains
human consumable text, this is most-likely what you'll want.
innerHTML gets the content of the element, including any HTML CONTENT. Use this when the element in question contains HTML content
that you want as HTML, rather than text. While using innerHTML
instead of textContent works, it is a slightly more expensive
operation to perform because you are asking the HTML parser to parse
the contents, so don't use innerHTML on non-HTML content.
Here's a sample of all 3 of the above used correctly:
window.addEventListener("DOMContentLoaded", function(){
document.querySelector("button").addEventListener("click", function(){
var input = document.getElementById("txtTest");
var parent = document.getElementById("parent");
// textContent will get the text characters as they are:
var textOnly = console.log("textContent of parent div is: " + parent.textContent);
// innerHTML will get the content of the element but will parse its HTML:
var htmlContent = console.log("innerHTML of parent div is: " + parent.innerHTML);
// value is ONLY for form-field elements:
console.log("The value of the div is: " + parent.value); // undefined
console.log("The value of the textbox is: " + input.value);
});
});
<input id="txtTest" type="text" placeholder="type in me and then click the button">
<div id="parent">
<p>Nested child HTML</p>
</div>
<button>Click me to get results</button>
So, if your scenario is that the content is in, say a textbox, your solution would be to use value, like this:
var firstAuthorName = document.getElementById("firstAuthorName");
var button = document.querySelector("button");
button.addEventListener("click", function(){
console.log("The first character in the textbox is: " + firstAuthorName.value.slice(0,1));
});
<input id="firstAuthorName" type="text" placeholder="type in me and then click the button">
<button>Click Me</button>

How can I format text in an HTML <textarea>?

I have a <textarea> on my page, and when I click a button, the value of the text in the textarea is assigned to .innerHTML of a paragraph on my page.
Now let's say I type something like this in the textarea:
Hey
how's
it
going
?
The paragraph would look like this
Hey how's it going ?
Basically, it wouldn't have <br> tags at the end of each row. Is there a way I can force the JavaScript function to insert <br> tags at the end of each row of my textarea, or is there an easier way to do this?
JavaScript code:
document.getElementById("sendMsgBtn").onclick = function(){
var element = document.createElement("p");
element.style.borderBottom = "1px solid black";
var content = document.createTextNode(document.getElementById("currentMsg").value);
content = content.replace(/\n/g, "<br>");
element.appendChild(content);
document.body.appendChild(element);
document.getElementById("currentMsg").value = "";
}
You don't want line breaks. Trust me.
Just set this:
white-space: pre-wrap;
This CSS will make whitespace significant, preserving it as it was typed.
When you copy the element from the textarea to the paragraph tag, replace all line breaks with <br> tags:
var input = document.getElementById("myTextarea").innerHTML; // get textarea contents
input = input.replace( /\n/g, "<br>"); // replace line breaks with <br> tags
document.getElementById("myParagraph").innerHTML = input; // place html-ified input into your <p>
If you are using jQuery, try this:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Then nl2br(yourVariableWithContent); can be used to change newline characters (the ones that the return button makes) into <br/>.

JavaScript, the use replace

var text_source="<a href='c:/exam_file.xls' target='_blank'>file downdload</a>";
text_search="file";
text_source.replace(new RegExp(text_search, 'gi'),
"<span style='font-weight:bold'>" +
text.toLowerCase() + "</span>");
The "a tag" link address has also changed:
<span style='font-weight:bold'>file</span> download
But, It should look like this. I have to change the text value in the "a tag".
<span style='font-weight:bold'>file</span> download
I will address what I said in a second, but you can do this without a loop with just pure regex. Below is how I accomplished this:
var text_source = "<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search = "dosya";
var patt = new RegExp("(<a .*?>)(" + text_search + ")(.*?</a>)","gi");
var text_source = text_source.replace(patt, function(match, $1, $2, $3) {
return $1 + "<span style='font-weight:bold'>" + $2.toLowerCase() + "</span>" + $3;
});
document.write(text_source);
DEMO
​
Getting back to what I said earlier, however, html can be a very, very complex language, and although regex can be used to parse it, partially, it should not be used for large quantities of data. Some patterns are too intricate to match against.
To ensure that your RegExp runs only against the content of the elements, you will need to select all of the elements that you want to manipulate and check their contents.
As an example:
var regExp = /dosya/ig;
[].slice.call(document.getElementsByTagName('a'), 0).forEach(function(element) {
if(regExp.test(element.textContent)) {
element.innerHTML = element.textContent.replace(regExp, function(text) {
return '<span style="font-weight: bold">' + text.toLowerCase() + '</span>';
})
}
});
There is also a jQuery pseudo selector :contains that does a similar thing.
Whilst the replies about not using regexes with HTML or XML are on the whole, correct, you could use the following for simple cases where you don't have too many nested tags:
var text_source="<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search="(<[^>]*>[^<]*)(dosya)([^<]*<[^>]*>)";
var replaced = text_source.replace(new RegExp(text_search, 'gi'), "$1<span style='font-weight:bold'>$2</span>$3");

Categories