How can I get the text between 2 elements - javascript

<div class="container">
asd
[I want get this text]
asd
Anouther text i dont need.
</div>
How can I withdraw the text between elements (not the inner text of elements, in this case I should get "[I want get this text]")?

DEMO
I think the simplest way would be to deal with the native dom elements:
var a = $(".container a")[0];
var textNode = a.nextSibling;
var text = textNode.textContent;
Note that var text = textNode.nodeValue; will also work, but I'm not sure which is preferable.

One way is to enclose the part in a span tag and get the contents of the span:
<div class="container">
asd
<span id="i_want_this">[I want get this text]</span>
asd
Anouther text i dont need.
</div>
myVal = $("#i_want_this").html();

Related

Replacing words with another word using javascript

I have the following code. I'm trying to change all instances of hello to hey. I have created a variable text to store the string. I have then tried the replace method on that string, but it does not change the string. I want the text in the <p> element tags to be changed to hey hey hey hey, but it does not change. What am I doing wrong?
HTML:
<p id="1">hello hello hello hello</p>
Javascript:
var text = document.getElementById("1").textContent;
text = text.replace(/hello/g,"hey");
You could do like this .
Why not working
For that initial call text= elem.textContent its read the value.
On the second time set text=replace value is not possible .Because the text only have string p elem not a DOM elem
var text = document.getElementById("1").textContent;
console.log(text) //direct string
text = text.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>
Solution
var text = document.getElementById("1");
console.log(text) //dom element
text.textContent = text.textContent.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>

Adding content into an element in html using javascript

I want to create a paragraph element and add content to it. Basically i want to let the textContent of a paragraph element be a string.
What i have tried doing is:
var st="Hello";
con=document.getElementById("content");
var pv=document.createElement("p");
con.appendchild(pv);
pv.setAttribute("",st);
<span id="content"> </span>
What attribute should i use to add in the setAttribute function here? I tried using textContent but it's not an attribute. Any other way i can do this?
You could do with elem.innerText instead of setAttribute
var st = "Hello";
var con = document.getElementById("content");
var pv = document.createElement("p");
con.appendChild(pv);
pv.innerText= st;
<span id="content"> </span>
You should use innerText to do this.
pv.innerText = "hello"
You can set and get the text value of an element using innerText.
More info on innerText can be found here:
https://www.w3schools.com/jsref/prop_node_innertext.asp
You can also use innerHTML which can change not just the text but also the HTML.
let con_txt = document.getElementById("content_text");
let pv_txt = document.createElement("p");
con_txt.appendChild(pv_txt);
pv_txt.innerText = "From innerText";
let con_html = document.getElementById("content_html");
let pv_html = document.createElement("p");
con_html.appendChild(pv_html);
pv_html.innerHTML = "<b>innerHTML also works!</b>"; //You can use HTML tags here
<span id="content_text"></span>
<span id="content_html"></span>
Above result in HTML
<span id="content_text">
<p>From innerText</p>
</span>
<span id="content_html">
<p><b>innerHTML also works!</b></p>
</span>
More info about innerHTML

Finding text within a span that contains tags and white spacing using jquery

I have the following span that contains white-spacing and text within tags - in this case a sup tag and a p tag:
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
I'm trying to extract 'Dr. J W Smith' from the element, but can't figure out how to do this. So far I have this:
jQuery('span[class="teamName"]').text(), which gives me the following output:
"
Dr.J
W
Smith
Throat specialist
"
This is as far as I got, I was thinking about stripping away the white spacing and placing each word in an array and then remove the last entry, does anybody have any ideas on how to go about this?
The simplest way is probably to clone the element, remove the br and p from it, and then get its text, replace any spans of whitespace with just a single space, and trim it:
// Here I'm assuming you have more than one
// of these, so this produces an array
var names = jQuery("span.teamName")
.clone()
.find("br, p").remove().end()
.map(function() {
return $(this).text().replace(/\s+/g, " ").trim();
}).get();
console.log(names);
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you just have one, we can avoid the map:
// Here I'm assuming you have more than one
// of these, so this produces an array
var name = jQuery("span.teamName")
.clone()
.find("br, p").remove().end()
.text()
.replace(/\s+/g, " ")
.trim();
console.log(name);
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use clone() function
var cloned = $('.teamName').clone();
cloned.find('p').remove();
console.log(cloned.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
This may work for you.
var $span = $('.teamName').clone();
$span.find('p').remove();
alert($span.text().replace(/[ \n]+/g, ' '));

Can part of Text node be highlighted?

I am creating Text node like var liContent = document.createTextNode(someHtmlString);.
And then add this variable into list like $("<li/>").html(liContent).appendTo(targetUnorderList);
Question is: Can I highlight some text in the liContent item?
And if "Yes" - how can I do that?
Clarification: I need to highlight partial content within li. For example, word Nice.
Update:
At the same time I need to display all content of Text node just like a text (including html tags).
Update 2: No processing is allowed on the string which need to be displayed. Seems there are no solution, because Text node is interpreted by browser just like a plain text.
Whole code example (working):
var someHtmlString = "<i class='icon-window-add'>Nice text here</i>";
var targetUnorderList = $("#targetUnorderList");
var liContent = document.createTextNode(someHtmlString);
$("<li/>").html(liContent).appendTo(targetUnorderList)[0];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<ul id="targetUnorderList"></ul>
</div>
Yes you could just create a custom class highlight then wrap the text you want to highlight by span with this class, Since you're using jQuery it could be done simply like :
$("<li/>").html("<i class='icon-window-add'>Nice <span class='highlight'>text here</span></i>");
Hope this helps.
var li = $("<li/>").html("<i class='icon-window-add'>Nice <span class='highlight'>text here</span></i>");
$("#targetUnorderList").append(li);
.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="targetUnorderList"></ul>
</div>
try this , it will show the "highlighted text" in red color
var someHtmlString1 = "<i class='icon-window-add'>Nice ";
var someHtmlString2="Highlighted text</span>";
var someHtmlString3="here</i>";
var targetUnorderList = $("#targetUnorderList");
var span1Text=document.createTextNode(someHtmlString1);
var span3Text=document.createTextNode(someHtmlString3);
var li=$("<li/>");
var span1=$("<span/>").html(span1Text).appendTo(li);
var span2=$("<span style='color:red'/>").html(someHtmlString2).appendTo(span1);
var span3=$("<span/>").html(span3Text).appendTo(li);
li.appendTo(targetUnorderList)[0];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<ul id="targetUnorderList"></ul>
</div>

Replace text, and replace it back

I am using this code to replace text on a page when a user clicks the link. I would like a way to replace it back to the initial text using another link within the replaced text, without having to reload the page. I tried simply adding the same script within the replaced text and switching 'place' and 'rep_place' but it didn't work. Any ideas? I am sort of a novice at coding so thanks for any advice.
<div id="place">
Initial text here
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</div></span>
Where do you store the original text? Consider what you're doing in some simpler code...
a = 123;
b = 456;
a = b;
// now how do you get the original value of "a"?
You need to store that value somewhere:
a = 123;
b = 456;
temp = a;
a = b;
// to reset "a", set it to "temp"
So in your case, you need to store that content somewhere. It looks like the "source" is a hidden element, it can just as easily hold the replaced value. That way values are swapped, not just copied. Something like this:
function replaceContentInContainer(target,source) {
var temp = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
document.getElementById(source).innerHTML = temp;
}
So replace them you simply call:
replaceContentInContainer('place', 'rep_place')
Then to swap them back:
replaceContentInContainer('rep_place', 'place')
Note that this will replace the contents of the "source" element until they're swapped back again. From the current code we can't know if that will affect anything else on the page. If so, you might use a different element to store the original values. That could get complex quickly if you have a lot of values that you need to store.
How's this? I store the initial content in an element of an array called initialContent.
<div id="place">
Initial text here [replace]
</div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here [revert]
</span>
</div>
<SCRIPT LANGUAGE="JavaScript">
var initialContent = [];
function replaceContentInContainer(target,source) {
initialContent[target] = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function showInitialContent(target) {
document.getElementById(target).innerHTML = initialContent[target];
}
</SCRIPT>
Working example: http://jsbin.com/huxodire/1/
The main changes I did were the following:
I used textContent instead of innerHTML because the later replaces the whole DOM contents and that includes removing your link to replace the text. There was no way to generate that event afterwards.
I closed the first div or else all the text would be removed with the innerText including the text that works as a link.
You said you wanted to replace back to the original text, so I used a variable to hold the last value only if this existed.
Hope this helps, let me know if you need more assistance.
The div tags were mixed up and wiping out your link after running it. I just worked with your code and showed how you could switch.
<div id="place">
Initial text here
</div>
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML =
document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div>
<div class="text" onClick="replaceContentInContainer('place', 'original_place')">
<u>Link to restore text</u></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</span>
<span id="original_place">
Initial text here
</span>
</div>

Categories