How to replace a text with a certain ID with javascript - javascript

I am doing some beginner exercises with JavaScript in order to learn but I'm coming up with an issue.
What I am trying to accomplish is replacing text with a certain ID. I have a 3 links all with text "Quote" which with their own ID(q1,q2,q3). However the function that I am calling is replacing the first instance of "Quote" so the issue is obviously my function.
How can I make it so that it only replaces that ID "Quote".
This is my function:
function quotation(c){
if ( c == q1){
var x = document.getElementByID("q1");
document.body.innerHTML = document.body.innerHTML.replace(x.innerHTML, 'Hello World');
}

Based on your code, I framed the HTML as
<a id='q1'>Quota</a>
<a id='q2'>Quota</a>
<a id='q3'>Quota</a>
As per your code, you're changing the text of the q1 element. So it was working as expected. Due to some edge case I messed my answer. Now What you need to do is simply add a class to your a tags like
<a id='q1' class='q'>Quota</a>
<a id='q2' class='q'>Quota</a>
<a id='q3' class='q'>Quota</a>
And within your function, iterate each elements; so that you can replace for all the elements.
var x = document.getElementsByClassName("q");
for (var i = 0; i < x.length; i++) {
document.body.innerHTML = document.body.innerHTML.replace(x[i].innerHTML, 'Hello World');
}
JSFiddle
Hope you understand.

If I understand the question correctly, it is as simple as this JSFiddle:
<a id="q1" href="#">Quote</a>
<a id="q2" href="#">Quote</a>
<a id="q3" href="#">Quote</a>
<script type="text/javascript">
function quotation(id, text) {
var q = document.getElementById(id);
if (q) q.innerHTML = text;
}
quotation('q1', 'Hello World');
</script>

Related

How to Javascript to replace HTML text with new text when the HTML may have children elements

I am trying to use JavaScript to search through all of the p elements to find a regular expressions, but the text that I am looking for may or may not partially exist in an attribute element or contained within a span. Ultimately, I plan to fix the cross references in the HTML code that were applied in Word to a Word bullet item by adding an attribute element with a reference to an html id that I have previously inserted with JavaScript.
My overall project is to create a Word document that I use the Save As function to have Word create a filtered HTML file. I am ultimately using JavaScript to insert ids and tags so that I can utilize a CSS file to standardize formatting of all my HTML files. Due to this, I have limited control of the initial HTML code.
Thus far I have been able to create a loop through all of the p elements. Within the loop, I am able to do a conditional statement for the regular expression on the innerText for "/Step (\d+)/" since I expect that the text will look something like Step 1, Step 12, or any other number. The code below seems to successfully enter if statement. I am running into trouble with the replace function for the innerHTML portion because the innerText matches the expression, but the innerHTML contains the element that prevents the final results that I am looking for. I would like to be able to generically account for any other element such as bold, italics, a, etc. To account for this, I have tried to use multiple if statements to replace various potential HTML conditions.
I am trying to figure out this skill by just being able to apply bold to the text to ensure that I understand how to complete this particular function. So far all of the searches that I have done have helped get the regular expression to match the innerText, but I can't find a method or ignoring the extraneous html code. I was thinking that it might be possible to store replaced innerText with the new HTML code and then make that the new innerHTML, but there could be other formatting in the p element that I want to maintain.
With the approach that I am taking to use a second regular expression for the innerHTML replace, the greedy search it seems like I would catch false results even if the regular expression was catching it.
HTML
<p id="FirstPara" class=firstpara>This is a header</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎ </span><b>1</b>.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>2.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>1 and Step <span lang=HE>‎</span>2.</p>
JavaScript function
function findTheText() {
regExp1 = /Step (\d)/g;
for (var i = 0; i < document.getElementsByTagName('p').length; i++) {
alert(i+" - "+j+" - "+document.getElementsByTagName('p')[i].innerHTML+" - "+results[j]);
var results = document.getElementsByTagName('p')[i].innerText.match(regExp1);
if (results !== null) {
for (var j = 0; j < results.length; j++) {
var replace = results[j].replace(/Step\s/,"");
var regExp2 = new RegExp('Step\s'+replace,"i");
var regExp3 = new RegExp('Step\s.*>'+replace,"i");
var regExp4 = new RegExp('Step\s.*>.*>'+replace,"i");
var results2 = document.getElementsByTagName('p')[i].innerText.match(regExp2);
var results3 = document.getElementsByTagName('p')[i].innerText.match(regExp3);
var results4 = document.getElementsByTagName('p')[i].innerText.match(regExp4);
if (results2 !== null) {
document.getElementsByTagName('p')[i].innerHTML.replace(regExp2, "<b>"+results[j]+"</b>");
} else if (results3 !== null) {
document.getElementsByTagName('p')[i].innerHTML.replace(regExp3, "<b>"+results[j]+"</b>");
} else if (results4 !== null) {
document.getElementsByTagName('p')[i].innerHTML.replace(regExp4, "<b>"+results[j]+"</b>");
}
}
}
}
}
As of now the code will find the text that I want, but since the regular expression matches the strings that I am looking for, but the innerHTML does not I am not achieving the bold (or eventually attributes) on the text.
Expected HTML output
<p class=firstpara>This is a reference to <b>Step 1</b>.</p>
<p class=firstpara>This is a reference to <b>Step 2</b>.</p>
<p class=firstpara>This is a reference to <b>Step 1</b> and <b>Step 2</b>.</p>
You might remove all child spans and then check the textContent to ignore the rest of the markup (like <b>s), capturing the step digit and replacing with that surrounded by <b> and </b>:
document.querySelectorAll('p').forEach((p) => {
p.querySelectorAll('span').forEach(span => span.remove());
p.innerHTML = p.textContent.replace(/Step +(\d+)/g, '<b>Step $1</b>');
});
<p id="FirstPara" class=firstpara>This is a header</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎ </span><b>1</b>.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>2.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>1 and Step <span lang=HE>‎</span>2.</p>
To only remove spans with a lang of HE:
document.querySelectorAll('p').forEach((p) => {
p.querySelectorAll('span[lang="HE"]').forEach(span => span.remove());
p.innerHTML = p.textContent.replace(/Step +(\d+)/g, '<b>Step $1</b>');
});
<p class=firstpara>This is a <span>reference</span> to Step <span lang=HE>‎ </span><b>1</b>.</p>
I am not really sure this is the result you expect, but this code may work. You can even update it to use arrow functions and template literals.
function findTheText() {
let regExp1 = /Step (\d)/g;
let paragraphs = document.getElementsByTagName('p');
for (var i = 0; i < paragraphs.length; i++) {
let spans = Array.from(paragraphs[i].getElementsByTagName('span'));
spans.forEach(function(child) {
paragraphs[i].removeChild(child);
})
if (paragraphs[i].innerHTML.match(regExp1)) {
let replace = paragraphs[i].innerHTML.match(regExp1);
replace.forEach(function(match) {
paragraphs[i].innerHTML = paragraphs[i].innerHTML.replace(match, "<b>" + match + "</b>");
})
};
}
}
findTheText()
<p id="FirstPara" class=firstpara>This is a header</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎ </span>1.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>2.</p>
<p class=firstpara>This is a reference to Step <span lang=HE>‎</span>1 and Step <span lang=HE>‎</span>2.</p>

how to post HTML code without the browser rendering

I'm to build a forum for the project, but right now I'm facing this problem where I want users to be able to post their HTML source code as it works in this forum.
But the problem is that the code runs or scatters my design when retrieve from my DB.
I tried using repalce() in jQuery but I could only replace < with < but I want a function to be able to replace others such as >,",' and & so my question is how can I update this function.
function convert(div){
var str = $(div).html();
var str2 = str.replace(/</g,"<");
var sta = $(div).html(str2);
return sta;
}
The above code work to replace the < but when I try including >,",' and & in the function it will stop work how can i make it work.
Thanks in advance.
Stick it in <pre> or <code> tags, or both, and make sure you use text() when inserting the content to the tag
function convert(div){
var str = $(div).html();
var sta = $('<code />', {text : str});
return sta;
}
var result = convert( $('#test') );
$('#result').html(result)
#result {
white-space : pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<span>
<p>TEST</p>
</span>
</div>
<br />
<div id="result">
<code> will preserve the code, and <pre> will preserve whitespace, but there's also the CSS white-space property, that can act as a <pre> tag using the pre setting

How to pass a Javascript variable to the NAME attribute of an HTML <a href> tag?

I am trying to pass a JavaScript variable to the NAME attribute of a HTML tag. For example, say I had a script like this:
<script>
var name = "Click here!";
</script>
I then want to pass that to some code such that
<name>
would produce a link to google that was displayed as "Click here!"
Using jQuery it would look like this:
<a id="linkToGoogle" href="www.google.com"></a>
and in your script
$('#linkToGoogle').text('Click here!');
Add an ID to the <a> tag, then add this to your script (script uses example ID mylink):
document.getElementById("mylink").innerHTML = name;
Add the ID like so:
Add class="change-name" to the elements that you want to change.
This text will be replaced
And then do:
var new_text = "Click here!";
var elems = document.querySelector('.change-name');
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].innerHTML = new_text;
}

add dynamic id to links using Javascript?

I have many links on a page generated dynamically. Now I want to attach ids to them based on a link just before them.
I have written the following function to return me the value I want to add as id to the href I want.
<script>
function movingid(){
var res = location.href.replace(/.*student\/(.*)\/subject/, '$1');
var subjectid = res.split("/")[2];
var classid = res.split("/")[1];
var sectionid = res.split("/")[0];
return classid+"-"+sectionid+"-"+subjectid;
}
</script>
So what I did is
<a href="javascript:void(0);" id= "javascript:movingid();" >Move To</a>
But the HTML thus generated is not calling the function. Instead its adding the id as plain text form like this id= "javascript:movingid();". How can I call the function?
Please help
Create the links this way:
<a href="javascript:void(0);" id= "" >Move To</a>
Maybe wrapping the links with a div, which gets the id "mylinks". After this call a function adding the id with this code:
i = "1";
$( "div#mylinks a" ).each(function( index ) {
$(this).attr("id",i);
i++;
});
Instead of i take your code from the movingid function you already posted.

Javascript / Jquery. Substitute plain text with html using regular expression with wildcard

I want to replace the plain text (for example) [next 1272] with
<a href='page.asp?id=1272'>
<img src='next.png' alt='Next Page' title='Next Page' />
</a>
The text could appear anywhere in the page html, and more than once, perhaps with a different number (from 1 to 99999). I don't have control of how/where it might appear.
Along the lines of
var ThisBody = $("body").html()
var regex = new RegExp("\\[ (I dont know) \\]", "g");
StrToReplaceWith = "...(the html in the example, with correct number)..."
ThisBody = ThisBody.replace(regex,StrToReplaceWith);
$("body").html(ThisBody);
Well I thought about it, and the following works, in case it's any help to anybody.
Not very elegant though
regex = new RegExp(/\[next (.*?)\]/gi);
mtch=ThisBody.match(regex)
newBody=ThisBody
if (mtch!=null)
{
if (mtch.length>0)
{
for (var i=0; i<mtch.length; i++)
{
tmp=mtch[i] // [next 1272]
tmp=tmp.replace("]","") // [next 1272
tmp=tmp.substring(6) // 1272
t="<a href='page.asp?id=" + tmp + "'>"
t+="<img src='Next.png' alt='Next Page' title='Next Page' />"
t+="</a>"
newBody=newBody.replace(mtch[i],t)
}
}
}
ThisBody=newBody

Categories

Resources