I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});
Related
Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.
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
I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:
<p>hello <h1> World </H1> </p>
for element "P" the right output should be ONLY "hello ".
I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").
Thanks,
Considering this HTML:
<div id="gettext">hello <p> not this </p> world?</div>
do you want to extract "hello" AND "world"? if yes, then:
var div = document.getElementById('gettext'), // get a reference to the element
children = [].slice.call(div.childNodes), // get all the child nodes
// and convert them to a real array
text = children.filter(function(node){
return node.nodeType === 3; // filter-out non-text nodes
})
.map(function( t ){
return t.nodeValue; // convert nodes to strings
});
console.log( text.join('') ); // text is an array of strings.
http://jsfiddle.net/U7dcw/
well behind it is an explanation
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.
<p >hello<h1>World</h1> </p>
This line will be rendered as
hello World
If you look at this code it will be as follow
<p>hello</p>
<h1>World</h1>
<p></p>
With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element.
Check this article
Now you can select the content of the first p tag simply by using the following code
var p = document.getElementsByTagName('p');
console.log(p[0].textContent);
JS FIDDLE
You can use the childNodes property, i.e.:
var p = document.querySelector('p');
p.childNodes[0]; // => hello
jsFiddle
Change your html to
<p id="id1">hello <h1> World </h1> </p>
Use this script,
alert(document.getElementById("id1").firstChild.nodeValue);
Try to provide id for the element which you want to do some operation with that.
Below is the working example, it show output as "hello" as you expected.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
alert(document.getElementById('test').innerHTML);
}
</script>
</head>
<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>
</html>
Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.
The function below loops over all element in document and prints just #text items
function myFunction()
{
var txt="";
var c=document.body.childNodes;
for (i=0; i<c.length; i++)
{
if(c[i].nodeName == "#text")
txt=txt + c[i].nodeName + "<br>";
};
return txt;
}
EDIT:
As #VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.
How can i change followed given HTML code via javascript and jQuery:
<div> <strong> unimportant text here </strong> important text here </div>
Goal is to change the Text in the <div> .... important text here </div> without touching the ...
<strong> unimportant text here </strong>
...part
Example:
*unimportant text here * important and changed text here
jsFiddle Demo
This requires having access to the parent div. I am not sure how you would like to access it, but for example, I will use an id.
<div id="d"> <strong> unimportant text here </strong> important text here </div>
This allows for the inner element to targeted. You should just use substring in order to select the latter part of the text
var AllText = $('#d').text();
var StrongElementText = $('#d strong').text();
var ImportantText = AllText.substr(StrongElementText.length);
Edit
With no way to target the element directly, it will have to be inferred (which can lead to target collision)
jsFiddle Demo Using Inferred target
$('div strong').each(function(){
var AllText = this.parentNode.innerText;
this.parentNode.innerText += " And Changed";
var StrongElementText = this.innerText;
var ImportantText = AllText.substr(StrongElementText.length);
c[0].innerHTML += ImportantText + "<br>";//shows output
});
<div>
<strong> unimportant text here </strong>
<span id="changeText">important text here</span>
</div>
$('#changeText').text= "I CHANGE THE TEXT";
With JavaScript I want to remove a specific DOM node and replace it with the innerHTML. For example I want to change
<div>
...
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
...
</div>
To
<div>
...
this is <b> the text </b> I want to remain.
...
</div>
Try this:
var oldElem = document.getElementById('t1');
oldElem.innerHTML = 'this is <b> the text </b> I want to remain.';
var parentElem = oldElem.parentNode;
var innerElem;
while (innerElem = oldElem.firstChild)
{
// insert all our children before ourselves.
parentElem.insertBefore(innerElem, oldElem);
}
parentElem.removeChild(oldElem);
There is a demo here.
This is effectively the same thing as .replaceWith() from jQuery:
$("#t1").replaceWith('this is <b> the text </b> I want to remain.');
var t1 = document.getElementById("t1");
t1.outerHTML = "this is <b> the text </b> I want to remain.";
http://youmightnotneedjquery.com/#replace_from_html
If you are using jQuery, you can try
var inner = j$("#t1").html()
$('#t1').replaceWith(inner);
This works:
var t1 = document.getElementById("t1");
t1.parentNode.innerHTML = t1.innerHTML;
Edit:
Please note that if the parent of t1 has any other children, the above will remove all those children too. The following fixes this problem:
var t1 = document.getElementById("t1");
var children = t1.childNodes;
for (var i = 0; i < children.length; i++) {
t1.parentNode.insertBefore(children[i].cloneNode(true), t1);
}
t1.parentNode.removeChild(t1);
It's very easy actually:
let span = document.getElementById('id');
span.outerHTML = span.innerHTML;
I just modified the HTML Like this.
<div>
<div id="t0">
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
</div>
</div>
And you do something like
document.getElementById("t0").innerHTML = "this is <b> the text </b> I want to remain.";
Hope it works
you might want to consider using jquery if that's possible.
it would make your life way way wayyyyyyyy easier.
once you have jquery, you can easily do this via
$("#t1").html("this is <b> the text </b> I want to remain.");
and if you find it a hassle to learn, you can always start by learning the jquery selectors.
you wouldn't know why you haven't been using it all this while :)
sorry if this is not what you want exactly..
~jquery addict
Updated:
To show what html text to put inside.
This is similar to the other answers but more functional.
go.onclick = () => {
[...t1.childNodes].forEach(e => {
t1.parentElement.insertBefore(e, t1);
});
t1.remove();
go.disabled = true;
}
#t1 {
color: red;
}
<div>
<div>BEFORE</div>
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
<div>AFTER</div>
<button id="go">GO</button>
</div>