How to replace text inside IDless <span> with javascript? - javascript

I have some text inside <span></span> tags and I want to change that text to something else when page is loaded.
So lets say default text is 'Story' (outputted by some CMS system and I can't edit it). So when page is loaded, .js detects that 'Story' word and replaces it with 'View This Story'.
Is that possible somehow?
Cheers
Update: I did search before asking and none of those methods I found works. Like I said the text is outputted by CMS and it gives wrong title, the title itself cannot be edited via CMS because it is used for other terms and tagging which is correct, so I was looking for js workaround to rename it on page load.
And span has no ID and I cannot give it any ID, because like I said it works as designed by CMS.
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
As you can see spans do not have IDs, but repeating classes only.

UPDATED as per OP request
You can replace any text within spans. You could even use regular expressions to make it more flexible, but let's leave this for now:
Native Javascript
var lookupSpanAndReplace = function(textFrom, textTo) {
var spans = document.getElementsByTagName('span');
for (i=0; i<spans.length; i++)
if (spans[i].innerHTML.indexOf(textFrom) >= 0)
spans[i].innerHTML = mySpan.innerHTML.replace(textFrom, textTo);
}
lookupSpanAndReplace("Story", "My New Text");
jQuery
var lookupSpanAndReplace = function(textFrom, textTo) {
$('span:contains(' + textFrom + ')').each(function(index, element) {
$(element).text($(element).text().replace(textFrom, textTo));
});
}
lookupSpanAndReplace("Story", "My New Text");

Try
$('#spanID').text("View This Story");
or if you want to replace a part of text
$('#spanID').text(function () {
return this.innerHTML.replace('Story', 'View This Story');
});

Give you span an ID and then run text([your new text]) on that node:
HTML
<span id="mySpan">Story</span>
jQuery
$('#mySpan').text("View This Story");
JSFiddle with jQuery
Or you can do it without jQuery:
document.getElementById("mySpan").innerHTML = "View This Story";
JSFiddle with plain 'ol Javascript

<script>
function changeSpan(){
var spans = document.getElementsByTagName ("span");
for (i = 0; i < spams.length; i++){
spans[i].innerHTML = textThatYouWant ();
}
}
</script>
<head onload="changeSpan()" >
<tile> ... </title>
</head>
<body>
...
</body>

Use the following to solve the issue.
HTML code:
<html>
<head>
<script>
function replace_text_span()
{
for(i=0;i<document.getElementsByTagName('span').length;i++)
{
document.getElementsByTagName('span')[i].innerHTML=document.getElementsByTagName('span')[i].innerHTML.replace("Story","View This Story");
}
}
</script>
<style>
</style>
</head>
<body onload="replace_text_span()">
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
</body>
</html>

Related

How do I replace instances of a word in multiple tags on page load?

Trying to replace a word that possibly will come in a foreach loop of a database items in razor view.
What I've tried so far
<section class="section bg-gray">
<div class="container">
<div class="row gap-y">
#foreach (var item in Model)
{
<div class="col-md-6 col-lg-4">
<div class="card d-block">
<p class="text-justify">#item.Text</p>
<p class="text-center mt-7">
<a class="btn btn-primary" href="#">Read more</a>
</p>
</div>
</div>
}
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elements = getElementsByClassName("text-justify");
$(elements).each(function(element) {
element.innerHTML = element.innerHTML.replace(/wordToReplace/g, 'newWord');
});
});
</script>
</div>
</section>
Excuse my poor JavaScript, I'm new on front-end. I looked for similar questions but closer topics are usually about replacing instances of a word in one tag. Please help.
You don't need jQuery for this - you can use document.querySelectorAll and just replace the desired text of the elements that match the selector.
Note that I have dodgied up a text element and for the desired class and replacing justify with justified to demonstrate the usage.
let elements = document.querySelectorAll(".text-justify");
elements.forEach(function(element){
let textContent = element.innerText;
let newTextContent = textContent.replace(/justify/g, 'justified');
element.innerText = newTextContent;
})
<p class="text-justify">This is a text with the class of text-justify</p>
<p>This is a text without the class of text-justify</p>
<p class="text-justify">This is a text with the class of text-justify</p>
You don't need jQuery for this - use a simple forEach loop. I've also refactored some other parts of your code (eg you were missing document:
document.getElementsByClassName("text-justify").forEach(element => element.innerHTML = element.innerHTML.replace(/word/g, "newWord"));
But if you really want to use jQuery:
$(".text-justify").html((index, element) => element.replace(/word/g, "newWord"));

Copy HTML from element, replace text with jQuery, then append to element

I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());

Find previous <a> element?

SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>

dynamically setting variables in html5 body?

Hi i am trying to dynamically set some of the contents of an html5 body with var strings defined in a JS.
below is what i have written so far and it doesnt seem to display the value specified.
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <var>name</var></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
i am trying to insert John Smith inside the "Your Name: text.
Thanks
You will have to use JavaScript to "print" the contents of a variable, to the HTML-source. Here's an example:
<div id="test"></div>
document.getElementById('test').innerHTML = 'This goes into the element!';
But since you're using jQuery, you could do this as well:
$('#test').text('This goes into the element!');
You should either give the VAR-Tag itself or it's wrapping LI-Tag an unique ID.
In HTML
<li>
<p>
<h3>Your Name: <var id="name">name</var></h3>
</p>
</li>
JavaScript
var name = "John Smith";
$("#name").text(name);
And by the way:
You shouldn't nest a Heading inside of a Paragraph, this doesn't make any sense.
Paragraphs are INLINE while Headings are BLOCKELEMENTS.
Check out this FIDDLE
You probably want something like below. Have global JS variables assigned, reference them with a VAR html5 tag, use JS at the end of body (or after DOM load) to substitute the keys in the VAR tags with the values held in the global VARS object.
<script>
VARS = {};
VARS.name = "John Smith";
VARS.age = 45;
</script>
...
Name : <var>name</var><br/>
Age : <var>age</var>
...
<script>
// run once at end of body
var all = document.getElementsByTagName("var");
for(var i=0; i<all.length; i++) {
var elm = all[i];
var key = elm.innerHTML;
if(VARS[key] != null)
elm.innerHTML = VARS[key];
else
elm.innerHTML = "";
}
</script>
The tag isn't supposed to be used this way
Try this:
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
$(document).ready(function() {
$("#name").text(name);
});
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <span id="name"></span></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
Edit: just to clarify one thing. The tag isn't supposed to be used to hold the place to the value of a variable. It's correct semantic meaning is more to represent a mathematical variable or a programming variable when you are showing some code on your page. If I'm wrong here, please someone correct me.
try this
$(document).ready(function() {
$("h3").text("Your name : John Smith");
});
Add some classes on your divs, to easuly select the good tags

how to hide/remove all text in-between two elements?

lets say i have this lump of HTML:
<div class="container">
<span class="title">Heading 1</span>
This is a description..<br />
This is the second line..
<div class="image"><img src="image.jpg" /></div>
</div>
What i want to do using jQuery/JavaScript is hide/remove all text and elements between <span class="title"> and <div class="image">.
I've looked all over and found pretty much nothing. Any ideas on how i could do this?
How about something like this? http://jsfiddle.net/ZW8q2/1
var foo = $('.container').children(':not(br)');
$('.container').html('').html(foo);
You could try:
var str = $('.container .title').text() + $('.container .image').html();
$('.container').html(str);
JS Fiddle.
Try this:
Place a tag around what you want to hide, give div an ID name. So in the end your will look like:
<div id = "hideMe" style ="display:block">...Your Content...</div>
Use this javascript:
function hide()
{
document.getElementById('hideMe').style.display = "none";
return;
}
Have the Javascript function called whenever you want to hide the stuff between the div from a button (or other control) like this:
<input type= "submit" onclick ="hide()">

Categories